Simulate first call fails, second call succeeds

Viewed 120622

I want to use Mockito to test the (simplified) code below. I don't know how to tell Mockito to fail the first time, then succeed the second time.

for(int i = 1; i < 3; i++) {
  String ret = myMock.doTheCall();

  if("Success".equals(ret)) {
    log.write("success");
  } else if ( i < 3 ) {
    log.write("failed, but I'll try again. attempt: " + i);
  } else {
    throw new FailedThreeTimesException();
  }
}

I can setup the success test with:

Mockito.when(myMock).doTheCall().thenReturn("Success");

And the failure test with:

Mockito.when(myMock).doTheCall().thenReturn("you failed");

But how can I test that if it fails once (or twice) then succeeds, it's fine?

6 Answers

I have a different situation, I wanted to mock a void function for the first call and run it normally at the second call.

This works for me:

Mockito.doThrow(new RuntimeException("random runtime exception"))
       .doCallRealMethod()
       .when(spy).someMethod(Mockito.any());

To add on to this and this answer, you can also use a loop to chain the mocked calls. This is useful if you need to mock the same thing several times, or mock in some pattern.

Eg (albeit a farfetched one):

import org.mockito.stubbing.Stubber;

Stubber stubber = doThrow(new Exception("Exception!"));
for (int i=0; i<10; i++) {
    if (i%2 == 0) {
        stubber.doNothing();
    } else {
        stubber.doThrow(new Exception("Exception"));
    }
}
stubber.when(myMockObject).someMethod(anyString());

The shortest would be

doReturn("Fail", "Success").when(myMock).doTheCall();
Related