我用 Java 开发了一个应用程序,我正在尝试使用 Powermockito 创建单元测试(我应该补充一点,我是单元测试的新手)。
我有一个名为 Resource 的类,它有一个名为 readResources 的静态方法:
public static void readResources(ResourcesElement resourcesElement);
ResourcesElement也是我编的。 在测试中,我想创建自己的资源,所以我希望上面的方法什么都不做。 我尝试使用此代码:
PowerMockito.spy(Resource.class);
PowerMockito.doNothing().when(Resource.class, "readResources", Matchers.any(ResourcesElement.class));
单元测试抛出异常:
org.mockito.exceptions.misusing.UnfinishedStubbingException: Unfinished stubbing detected here: -> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)
Powermockito 还建议我应该在 when 之后使用 thenReturn 或 thenThrow,但似乎方法“when”在 doNothing 之后调用时返回 void(这是合乎逻辑的)。 如果我尝试:
PowerMockito.when(Resource.class, "readResources", Matchers.any(ResourcesElement.class)).....
doNothing 不是什么时候之后的选项。
我设法使没有参数的方法不做任何事情,使用该方法的 2 个参数版本。例如:
PowerMockito.doNothing().when(Moduler.class, "startProcessing");
这有效(startProcessing 不接受任何参数)。
但是我怎样才能让那些接受参数的方法对 Powermockito 什么都不做呢?
最佳答案
您可以在下面找到一个功能齐全的示例。由于您没有发布完整的示例,我只能假设您没有使用 @RunWith
或 @PrepareForTest
注释测试类,因为其余部分似乎没问题。
@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!");
}
}
关于java - Powermockito doNothing 用于带参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22981048/