Simulate first call fails, second call succeeds

From the docs:

Sometimes we need to stub with different return value/exception for the same method call. Typical use case could be mocking iterators. Original version of Mockito did not have this feature to promote simple mocking. For example, instead of iterators one could use Iterable or simply collections. Those offer natural ways of stubbing (e.g. using real collections). In rare scenarios stubbing consecutive calls could be useful, though:

when(mock.someMethod("some arg"))
   .thenThrow(new RuntimeException())
  .thenReturn("foo");

//First call: throws runtime exception:
mock.someMethod("some arg");

//Second call: prints "foo"
System.out.println(mock.someMethod("some arg"));

So in your case, you'd want:

when(myMock.doTheCall())
   .thenReturn("You failed")
   .thenReturn("Success");

The shortest way to write what you want is

when(myMock.doTheCall()).thenReturn("Success", "you failed");

When you supply mutiple arguments to thenReturn like this, each argument will be used at most once, except for the very last argument, which is used as many times as necessary. For example, in this case, if you make the call 4 times, you'll get "Success", "you failed", "you failed", "you failed".


Since the comment that relates to this is hard to read, I'll add a formatted answer.

If you are trying to do this with a void function that just throws an exception, followed by a no behavior step, then you would do something like this:

Mockito.doThrow(new Exception("MESSAGE"))
            .doNothing()
            .when(mockService).method(eq());

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());

Tags:

Java

Mockito