I made a change in the blogger configuration to ease the later work when blogging. It is possible that older entries are not correctly formatted.

Friday 23 April 2010

Mockito - basics

This entry gives simple methods on how to use mockito.

Maven configuration

To add mockito-core to your configuration, update your dependencies with:

<!-- needs extra dependencies: objenesis & hamcrest -->
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.8.1</version>

In order to add the complete mockito framework, i.e. mockito-all, update your dependencies with

<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.1</version>

Of course if the mock code is only found in unit tests, then you might want to add:

<scope>test<scope>
to your pom.xml

Use of Mocks to verify interaction (Spying)

The following example is adapted from the mockito documentation

// the staic import allows the direct use of the help methods: mock and verify
import static org.mockito.Mockito.*;

// create a mock of a map
List mockedMap = mock(Map.class);

//using mock object
mockedMap.put("key", "value");
mockedMap.clear();
//verification
verify(mockedMap).put("key","value");
verify(mockedMap).clear();

Stubbing - Or Have your objects mock others

While the previous section was used to verify that some operation did occur on a specific object. In some cases, you may not wish to initialize completely a complex object. In such a case, you can use mockito to perform stubbing, i.e. mockito provides an interface, so that the object returns a specific value, when a call to a method is performed.

For instance, it is possible to use the mocking framework to return a given result for certain parameters:

when(mockedMap.get("key")).thenReturn("first");
when(mockedList.get(5)).thenThrow(new RuntimeException());