Search code examples
javamockitostub

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


I want to throw a specific exception for the first 5 times the method is executed. Afterwards, I want to throw another exception.

Ideally, I have this code snippet, which obviously doesn't work

int count = 0;
int max = 5;

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

How can I make it work?


Solution

  • You can use the thenThrow(Throwable... throwables) method on the OngoingStubbing instance returned by Mockito.when(...).
    The method accepts a var-args that are the exceptions to throw consecutively when the mocked method is invoked.

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

    or by chaining OngoingStubbing.thenThrow() invocations as the method actually returns a OngoingStubbing object :

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