49

I have a method of a mocked object that can be called multiple times (think recursion). The method is defined like this:

public void doCommit() { } 

In order to tell it to fail I use this convention:

doThrow(new RuntimeException()).when(mMockedObject).doCommit(); 

This though, makes the method throw this exception EVERY time it is called. How can I make it so that it only, for example, throws it the first and third time it is called? Which means that, for example, the second and forth time it just returns without throwing an exception. Please note that I am not the author of doCommit(), nor do I have source code that I can change.

2 Answers 2

73

I figured it out (with some hints from Igor). This is how you stub consecutive void method calls:

doThrow(new RuntimeException()).doNothing().doThrow(...).doNothing().when(mMockedObject).doCommit(); 

thanks Igor!

Sign up to request clarification or add additional context in comments.

1 Comment

with BDDMockito it would be willThrow(new RuntimeException()).willNothing().willThrow(...).willNothing().given(mMockedObject).doCommit();
24

Reading Stubbing Consecutive Calls doco, something like this might do it:

when(mMockedObject.doCommit()) .thenThrow(new RuntimeException()) .thenCallRealMethod() .thenThrow(new RuntimeException()) .thenCallRealMethod(); 

If you don't want to actually call the underlying method then you should use thenAnswer instead of thenCallRealMethod method and provide an empty stub imlementation.

3 Comments

I am not sure this will work (but you might be on to something). When I write this: when(mMockedUpdatingBatch.updateBatch()).thenThrow(new RuntimeException()); I get this compile error: The method when(T) in the type Mockito is not applicable for the arguments (void). I think that when() expects the mocked method to be non-void.
Perhaps it needs to be rewritten back to front if that's possible using doThrow().doCallRealMethod().when(mMockedObject).doCommit();?
If I mocked an interface and the thenCallRealMethod will not work, what is the concise thenAnswer invocation which will lead to the same effect as doNothing()?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.