JavaPowerMockito:拦截所有静态方法
此代码模拟类中的静态void方法并重写其行为。(摘自本问题here)
@RunWith(PowerMockRunner.class)
@PrepareForTest({Resource.class})
public class MockingTest{
@Test
public void shouldMockVoidStaticMethod() throws Exception {
PowerMockito.spy(Resource.class);
PowerMockito.doNothing().when(Resource.class, "readResources", Mockito.any(String.class));
//no exception heeeeere!
Resource.readResources("whatever");
PowerMockito.verifyStatic();
Resource.readResources("whatever");
}
}
class Resource {
public static void readResources(String someArgument) {
throw new UnsupportedOperationException("meh!");
}
public static void read(String someArgument) {
throw new UnsupportedOperationException("meh!");
}
}
如何拦截所有方法调用,而不是单独指定方法
它尝试了PowerMockito.doNothing().when(Resource.class)
和PowerMockito.doNothing().when(Resource.class, Matchers.anything())
,但这些都不起作用
# 1 楼答案
如果想模拟一个类的所有静态方法,我认为可以使用
PowerMockito.mockStatic(..)
而不是PowerMockito.spy(..)
:希望对你有帮助
# 2 楼答案
这是:
不起作用,因为
Matchers.anything()
为Object
创建了一个匹配器,而上面的when()
正在尝试根据类型查找方法。试着通过Matchers.any(String.class)
。这只适用于具有相同参数列表的静态方法。不确定是否有办法实现更通用的覆盖