Mockito,doNothing()的用法何时()

时间:2016-10-02 22:49:38

标签: java unit-testing mockito

我是Mockito的新手,我接过了这个例子,但是当它在方法的第一行调用doNothing()时,有一个我不明白的步骤:

@Test(expected = RuntimeException.class)
public void testConsecutiveCalls() throws Exception(){
  doNothing().doThrow(Exception.class).when(b).voidMethod();
  a.usesVoidMethod()
  verify(b).voidMethod();
  a.usesVoidMethod()
}

我确实理解当第一次调用voidMehtod()时没有返回任何内容,并且在第二次时它会给出异常。

但是如果我们删除doNothing.doThrow(Exception.class).when(b).voidMethod();,测试是否仍然有效并且将测试我们想要测试的方法,该方法在第二次引发异常?

2 个答案:

答案 0 :(得分:2)

doNothing方法不会改变mocked' method, but the declaration of the doThrow does. If you have a spy and don't want a method to be executed, then doNothing`的行为会改变行为。

答案 1 :(得分:2)

几点,编号只是为了便于参考:

  1. mock 的默认行为是每次返回一个合适的虚拟值,通常为零,null或空字符串。间谍的默认行为是调用间谍的真实实现。当然,通过@MockMockito.mock的参数,您可以使用任意答案或任何Mockito的standardadditional答案。

  2. 当多个动作作为链的一部分给出时,Mockito将按顺序执行每个动作并永远重复最后的动作。

    // calls to foo.bar() return 1, 2, 3, 3, 3...
    doReturn(1).thenReturn(2, 3).when(foo).bar();
    

    请注意,这是在同一个链中;最近定义的匹配链获胜,因此单独的语句不会产生相同的效果。

    doReturn(1).thenReturn(2).when(foo).baz();
    doReturn(3).thenReturn(4).when(foo).baz();
    // calls return 3, 4, 4, 4... because the first chain is entirely overridden.
    
  3. doNothing然后,从覆盖默认行为在链中设置操作中获取其大部分价值。

  4. 那么尝试做的测试是第一次doNothing以便验证成功,然后第二次doThrow来满足预期的异常。虽然失败的verify(正确)会因为Mockito's errors subclass Error and not Exception而无法通过测试,但是你是正确的,删除​​doNothing仍会导致测试通过在第一个上抛出异常致电a.usesVoidMethod()。虽然这对于测试来说已经足够了 - 毕竟,你可以在测试中看到doNothing - 一个更强大的测试可能看起来像这样:

    @Test
    public void testConsecutiveCalls() throws Exception(){
      doNothing().doThrow(SomeKnownException.class).when(b).voidMethod();
      a.usesVoidMethod();
      verify(b).voidMethod();
      try {
        a.usesVoidMethod();
        fail();
      } catch (SomeKnownException expected) { /* OK */ }
    }
    
相关问题