Annotations in Mockito


Using runner lets you save a little bit of coding (no need for @Before method). On the other hand using a runner is sometimes not possible, i.e. when you are already using one, like SpringJUnit4ClassRunner.

@Mock and @InjectMocks

@Mock creates a mock on each test method run, and @InjectMocks will pass mocks to any matching setters or constructors



private ArgumentCaptor<TargetClass> targetClassCaptor;

TargetClass= targetClassCaptor.getValue();

Stubbing void methods

We face a lot of scenarios in our applications where we need to stub void methods. With void methods, stubbing is slightly different. We cannot use void methods in the when() call.

The alternative syntax is:


We can also test exception handling. How would my code handle if an exception is thrown by void methods

Mockito.doThrow(new RuntimeException()).when(mock).setAttribute(Mockito.anyString());

We can also set the behaviour of a void method to do nothing when called. This is not possible for non-void methods:


Why when() does not work for void methods:

Take a look at the syntax of when():


Notice that the method is called inside brackets. Compiler does not like void method inside brackets!!

The two ‘when()’ are different syntax.

Notice that the when() for a non-void method stubbing takes in a methodCall as parameter, whereas the when() in void method stubbing takes in a mock object.

return Argument that is passed in:

If you have Mockito 1.9.5, there is a new static method that can make the Answer object for you. You need to write something like


or alternatively


Note that the returnsFirstArg() method is static in the AdditionalAnswers class, which is new to Mockito 1.9.5; so you’ll need the right static import.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s