【发布时间】:2014-11-26 05:59:49
【问题描述】:
我正在使用 Powermockito,mockito 和 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!
你能告诉我我在这里缺少什么吗?
谢谢
【问题讨论】:
-
也试过使用,PowerMockito.doAnswer
(){ @Override public void answer(){return null}}).when(obj).voidMethod(Matchers.any(..)) ;但仍然遇到同样的异常 -
您的 voidMethod 是最终方法吗?
-
另外,如果你使用
@Before而不是@BeforeClass是否有效? -
感谢 Sourabh 的回复。由于我使用的是 TestNG,所以我不能使用 @Before 注释,因为它用于 JUnit。我重写的 void 方法不是最终方法。