存根时ClassOne.methodOne,我收到以下关于存根具有返回值的 void 方法的错误消息,即使ClassOne.methodOne它不是 void。该错误似乎与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);
为什么会发生这种情况,我该如何解决?
当您尝试存根 Mockito 无法覆盖的方法时,可能会发生这种情况。根据语法的when工作方式,Mockito 将它可以检测到的最新调用标识为对 stub 的方法调用。如果 Mockito 无法检测到您正在存根的方法调用,但可以检测到在存根方法的实际实现中发生的模拟上的调用,那么它可能会将该调用误认为是存根调用。因此,它认为您正在ClassTwo.methodTwo使用返回值存根 void 方法,并抛出异常。
/* 1 */  when(classOne.methodOne("some string")).thenReturn(true);
/* 2 */  when(              false              ).thenReturn(true);
/* 3 */  (    internal mockito stub object     ).thenReturn(true);
通常,Mockito 调用classOne.methodOne,这是模拟上的未存根方法。Mockito 的默认实现检测调用,将调用记录为最后接收到的调用,并返回 false。然后,在上面的第 2 步中,Mockito 看到对 的调用when,将最后一次调用标记为存根,并准备调用 到thenVerb,这在第 3 步中出现。但是,在这种情况下,在第 1 步期间,Mockito 没有覆盖methodOne,因此它无法检测到呼叫或记录调用。它实际上调用classOne.methodOne,并且如果与模拟有任何交互,则这些交互会被记录下来,就好像它们在when调用上方的测试中一样。步骤 2 与之前一样进行,只是 Mockito 标记了对存根的错误调用,因此步骤 3 看到thenReturn对 void 方法的调用。
如果您使用匹配器,这可能会更加麻烦,因为如果内部匹配器堆栈上的匹配器数量错误,那么您可能会收到 InvalidUseOfMatchersException,即使测试中的存根调用似乎正确使用了匹配器。
当 Mockito 无法覆盖您正在存根的方法时,就会出现这个问题。您需要检查以下内容是否全部正确:
final,并且不应该有非public父母。static和非final。@InjectMocks,则它是一个真正的实现而不是模拟;在这里阅读更多。doReturn/ doAnswer/doThrow语法,因为否则你将调用间谍的实际方法从调用内when。| 归档时间: | 
 | 
| 查看次数: | 4576 次 | 
| 最近记录: |