对于带参数的方法,Powermockito doNothing [英] Powermockito doNothing for method with arguments
问题描述
我用Java开发了一个应用程序,我正在尝试使用Powermockito创建单元测试(我应该补充说我是单元测试的新手)。
I've developed an application in Java and I'm trying to create unit tests using Powermockito (I should add that I'm new to unit testing).
我有一个名为Resource的类,它有一个名为readResources的静态方法:
I have a class called Resource which has a static method called readResources:
public static void readResources(ResourcesElement resourcesElement);
ResourcesElement也由我编码。
在测试中,我想创建自己的资源,所以我希望上面的方法什么都不做。
我尝试使用此代码:
ResourcesElement is also coded by me. In testing, I want to create my own Resource, so I want the above method to do nothing. I tried using this code:
PowerMockito.spy(Resource.class);
PowerMockito.doNothing().when(Resource.class, "readResources", Matchers.any(ResourcesElement.class));
单元测试抛出异常:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
此处检测到未完成的存根:
- > at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore。 java:36)
org.mockito.exceptions.misusing.UnfinishedStubbingException: Unfinished stubbing detected here: -> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)
Powermockito还建议我应该使用thenReturn或者之后的Throw,但似乎方法'when'返回在doNothing之后调用它时是无效的(这是合乎逻辑的)。
如果我尝试:
Powermockito also suggest that I should use thenReturn or thenThrow after when, but it seems that the method 'when' returns void when it is called after doNothing (which is logical). If I try:
PowerMockito.when(Resource.class, "readResources", Matchers.any(ResourcesElement.class)).....
在什么时候不做任何选择。
doNothing is not an option after when.
我设法使用方法的2个参数版本创建没有参数的方法,什么都不做。例如:
I managed to make methods without arguments to do nothing, using the 2 arguments version of the method. For example:
PowerMockito.doNothing().when(Moduler.class, "startProcessing");
这有效(startProcessing不接受任何参数)。
This works (startProcessing doesn't take any arguments).
但是我怎样才能制作出能够使参数与Powermockito无关的方法?
But how can I make methods that do take arguments to do nothing with Powermockito?
推荐答案
你可以找到一个功能齐全的例子如下。由于您没有发布完整示例,我只能假设您没有使用 @RunWith
或 @PrepareForTest $注释测试类c $ c>因为剩下的就好了。
You can find a fully functional example below. Since you didn't post the complete example, I can only assume that you did not annotate the test class with @RunWith
or @PrepareForTest
because the rest seems fine.
@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!");
}
}
这篇关于对于带参数的方法,Powermockito doNothing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!