Powermock模拟void方法抛出错误 [英] Powermock mocking void method throws error
问题描述
我正在将Powermockito与TestNG一起使用.我的测试类扩展了PowerMockTestCase.我想模拟一个void方法.为此,我使用了以下示例语法,
I am using Powermockito, mockito with TestNG. My test class extends PowerMockTestCase. I want to mock a void method. For that I used following sample syntax,
@PrepareForTest(TestClass.class)
class Sample extends PowerMockTestCase{
@BeforeClass
public void beforeClass(){
TestClass obj = PowerMockito.spy(TestClass.getInstance());
PowerMockito.doNothing().when(obj).voidMethodName(Matchers.any(Type1.class), Matchers.anyString(), Matchers.any(Type2.class));
}
当我给这个时,我得到:
When I give this, I get :
FAILED CONFIGURATION: @BeforeClass beforeClass
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
你能让我知道我在这里想念什么吗?
Can you please let me know what I am missing here?
谢谢
推荐答案
如果void方法不是最终方法,则无需使用PowerMockito! 另外,我不明白为什么要嘲笑"doNoting()".如果您具有默认的模拟行为,则将使用此方法,当调用void方法时,并且对于特定的测试用例,您希望覆盖此行为时,将引发异常.如果您的情况是这样,将完全删除此行.
If the void method is not a final method, you do not need to use PowerMockito! Also, I don't see why you would mock "doNoting()". This would be used if you had a default mocking behavior, throwing an exception when the void method is called, and when for a specific test case you would want to override this behavior. Ib your case, would remove this line completely.
这篇关于Powermock模拟void方法抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!