Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only throw exception when the mocked method is called for the first time?

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.

like image 839
fnCzar Avatar asked Aug 16 '10 22:08

fnCzar


People also ask

Which Mockito methods are used to handle the exception in case of test methods?

Mockito + Catch-Exception + AssertJ.

How do you mock an exception to void method?

Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.

Why is mock method returning null?

If a method return type is a custom class, a mock returns null because there is no empty value for a custom class. RETURN_MOCKS will try to return mocks if possible instead of null . Since final class cannot be mocked, null is still returned in that case.


2 Answers

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!

like image 58
fnCzar Avatar answered Sep 20 '22 05:09

fnCzar


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.

like image 30
Igor Zevaka Avatar answered Sep 23 '22 05:09

Igor Zevaka