MOCKITO - 根据调用方法的次数更改抛出的异常

MOCKITO - Change the exception thrown based on number of times the method is called

我想在方法执行的前 5 次抛出特定异常。之后,我想抛出另一个异常。

理想情况下,我有这段代码,但显然行不通

int count = 0;
int max = 5;

@Test
public void myTest(){
   ...
   doThrow(count++ < max ? myException1 : myException2).when(myClass).myMethod()
   ...
}

我怎样才能让它发挥作用?

您可以使用 Mockito.when(...) 返回的 thenThrow(Throwable... throwables) method on the OngoingStubbing 实例。
该方法接受一个 var-args,这是调用模拟方法时连续抛出的异常。

@Test
public void myTest(){
   // ...
   Mockito.when(myClass.myMethod())
          .thenThrow( myException1, 
                      myException1, 
                      myException1, 
                      myException1, 
                      myException1,
                      myException2);
   // ...
}

或者通过链接 OngoingStubbing.thenThrow() 调用作为方法实际上 returns 一个 OngoingStubbing 对象 :

@Test
public void myTest(){
   // ...
   Mockito.when(myClass.myMethod())
          .thenThrow(myException1)
          .thenThrow(myException1)
          .thenThrow(myException1)
          .thenThrow(myException1)
          .thenThrow(myException1)
          .thenThrow(myException2);
   // ...
}

您可以 return 在第一次调用时出现异常,在第二次调用时出现其他情况:

when(myMock.myMethod(any()))
.thenThrow(new MyFirstException())
.thenThrow(new MySecondException())
.thenReturn(new MyObject();

这种方法在测试递归调用的方法时很有用。

最后我建议检查该方法的调用次数是否正确。

verify(myMock, times(3)).myMethod(any());