Powermock mocking void方法抛出错误

时间:2014-11-26 05:59:49

标签: testng mockito powermock

我正在使用Powermockito,使用TestNG进行模拟。我的测试类扩展了PowerMockTestCase。我想模拟一个void方法。为此我使用了以下示例语法

@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));
}

当我这样做时,我得到:

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!
你能告诉我这里缺少的东西吗?

由于

1 个答案:

答案 0 :(得分:0)

如果void方法不是最终方法,则不需要使用PowerMockito! 另外,我不明白为什么你会嘲笑" doNoting()"。如果您有默认的模拟行为,在调用void方法时抛出异常,并且对于特定的测试用例,您将希望覆盖此行为,则会使用此方法。在你的情况下,将彻底删除这一行。