【发布时间】:2016-02-12 23:20:06
【问题描述】:
当存根ClassOne.methodOne 时,我收到以下关于用返回值存根无效方法的错误消息,即使ClassOne.methodOne 不是无效的。该错误似乎与ClassTwo.methodTwo 相关,即使我正在存根ClassOne.methodOne。
org.mockito.exceptions.base.MockitoException:
`'methodTwo'` is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
doThrow(exception).when(mock).someVoidMethod();
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. The method you are trying to stub is *overloaded*. Make sure you are calling
the right overloaded version.
2. Somewhere in your test you are stubbing *final methods*. Sorry, Mockito does not
verify/stub final methods.
3. A spy is stubbed using `when(spy.foo()).then()` syntax. It is safer to stub
spies with `doReturn|Throw()` family of methods. More in javadocs for
Mockito.spy() method.
我的代码:
public class ClassOne {
private ClassTwo classTwo;
public boolean methodOne() {
classTwo.methodTwo();
return true;
}
}
我的测试:
when(classOne.methodOne("some string")).thenReturn(true);
为什么会发生这种情况,我该如何解决?
【问题讨论】: