我正在使用TestNG 6.8.8,Mockito 1.9.5和PowerMock 1.5.4。当我模拟最终的void方法时,测试有时会通过,并且有时会因错误UnfinishedStubbingException而失败。
这是PowerMock的错误吗?
public abstract class Parent implements Serializable {
protected abstract void validate();
public final void validateSomething() {
// some code here
}
}
@PrepareForTest({ Parent.class })
public class ParentTest {
@Test
public final void testSomeMethod() {
Parent parentObj = PowerMockito.mock(Parent.class);
doNothing().when(parentObj).validateSomething();
TestCodeThatResultsInCallToParentObj.validateSomething();
}
}
错误讯息:
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!
at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl.performIntercept(MockitoMethodInvocationControl.java:260)
答案 0 :(得分:0)
您可以使用委托并将该类的执行包装在您的类中。
class ParentWrapper {
private final Parent delegate;
ParentWrapper(Parent delegate) {
this.delegate = delegate;
}
void validateSth() {
delegate.validateSth();
}
}
现在您可以在没有任何Powermock的情况下模拟ParentWrapper。