此代码模拟类中的静态void方法并重写其行为。(取自此问题)
@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())
,但这些都不起作用。
这:
PowerMockito.doNothing().when(Resource.class, Matchers.anything())
不起作用,因为Matchers.anything()
为Object
创建了一个匹配器,而上面的when()
正试图根据类型查找方法。尝试传递Matchers.any(String.class)
。这只适用于具有相同参数列表的静态方法。不确定是否有更通用的替代方法。
如果你想模拟一个类的所有静态方法,我认为你可以使用PowerMockito.mockStatic(..)
而不是PowerMockito.spy(..)
:
@Test
public void shouldMockVoidStaticMethod() throws Exception {
PowerMockito.mockStatic(Resource.class);
//no exception heeeeere!
Resource.readResources("whatever");
PowerMockito.verifyStatic();
Resource.readResources("whatever");
}
希望它能帮助你。