此代码模拟类中的静态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()),但这些都不起作用。
发布于 2014-08-29 14:51:58
这一点:
PowerMockito.doNothing().when(Resource.class, Matchers.anything())不起作用,因为Matchers.anything()为Object创建了一个匹配器,而上面的when()正在尝试根据类型查找方法。尝试传递Matchers.any(String.class)。这只适用于具有相同参数列表的静态方法。不确定是否有更通用的覆盖方法。
发布于 2014-08-29 15:35:50
如果你想模拟一个类的所有静态方法,我认为你可以用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");
}希望能对你有所帮助。
https://stackoverflow.com/questions/25562865
复制相似问题