Annotations in Mockito

@RunWith(MockitoJUnitRunner.class)

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

@Captor


@Captor

private ArgumentCaptor<TargetClass> targetClassCaptor;

verify(myClass).doSomething(targetClassCaptor.capture());
TargetClass= targetClassCaptor.getValue();
assertThat(...);
assertTrue(...);

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:

Mockito.doReturn(result).when(mock).method();

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:

Mockito.doNothing().when(mock).method();

Why when() does not work for void methods:

Take a look at the syntax of when():

when(mock.method())

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

when(myMock.myFunction(anyString())).then(returnsFirstArg());

or alternatively

doAnswer(returnsFirstArg()).when(myMock).myFunction(anyString());

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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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