Mockito:了解when().thenThrow()函数如何工作

Wil*_*ire 5 java junit mockito

when(mockObj.method(param1, param2)).thenReturn(1);
when(mockObj.method(param1, param2)).thenReturn(2);
Run Code Online (Sandbox Code Playgroud)

当存在冲突的语句从模拟对象中具有相同参数列表的方法返回值时,我观察到将返回最近的when/thenReturn。所以,下面的陈述是正确的。

assertEquals(2, mockObj.method(param1, param2));
Run Code Online (Sandbox Code Playgroud)

当有冲突的语句抛出异常时,行为与上面不一样。例如,

@Test(expected = ExceptionTwo.class)
public void testMethod() {
    when(mockObj.method(param1, param2)).thenThrow(ExceptionOne.class);
    when(mockObj.method(param1, param2)).thenThrow(ExceptionTwo.class);
    mockObj.method(param1, param2);
}
Run Code Online (Sandbox Code Playgroud)

这个测试用例失败了。任何解释都会有帮助。

Dan*_*ran 6

在第一种情况下,正如此处提到的文档:

Warning : if instead of chaining .thenReturn() calls, 
multiple stubbing with the same matchers or arguments is used, 
then each stubbing will override the previous one.
Run Code Online (Sandbox Code Playgroud)

所以第二个将覆盖第一个。因此,返回2。其他情况,您可以参考这里

when(mock.foo()).thenThrow(new RuntimeException());

//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
when(mock.foo()).thenReturn("bar");

//You have to use doReturn() for stubbing:
doReturn("bar").when(mock).foo();
Run Code Online (Sandbox Code Playgroud)

当您使用when..thenReturn时,将调用存根方法。第一次您没有观察到它,因为它是在模拟对象上调用的。when但是当您第二次编写时,我们会有一些行为mock.foo()(您之前将其设置为抛出异常)。因此,第二个 when(..) 语句在您的情况下引发异常。所以你应该使用 doThrow().when(..).method(...) 代替。