Mock ObjectMapper.readValue() using Junit Mockito


This example will show you how to mock ObjectMapper.readValue() using Junit Mockito. When we write Junit test cases or classes, we generally do not test on real object that are injected into the class that has to be tested using Junit to avoid any test case failure at some point, instead we want to test the business logic out of the written code.

We will mock the ObjectMapper class in the same way we mock our external classes, such as, DAO, Repository or any other classes. Here we will create a simple example to show you how to mock ObjectMapper.readValue() using Junit Mockito.


Knowledge of Java, Junit

JDK 1.8, Spring API

Junit API, Jackson API

Example Implementation

Let’s move on to the example implementation…

DTO Class

The below class just holds some information about a user. The getters and setters have been removed from this example but actually these are required to run the example.

public class UserDto {
    private String id;
    private String name;
    private String email;
    //getters and setters
    public String toString() {
        return "UserDto [id=" + id + ", name=" + name + ", email=" + email + "]";

Spring Service Class

We create the Spring service class that has only one method and performs the update of user information. We autowired the Jackson’s ObjectMapper class.

Assuming, the method update() gets some information from the external source and convert the JSON string into UserDto and finally does some processing and saves to the permanent storage.

public class ObjectMapperServiceImpl {
    private ObjectMapper objectMapper;
	public void updateUser() throws JsonParseException, JsonMappingException, IOException {
        // assume below json string value comes from source
        final String json = "{\"id\":\"5000605\",\"name\":\"John Miller\",\"email\":\"\"}";
		UserDto userDto = objectMapper.readValue(json, UserDto.class);
		// do some processing with userDto and persist to permanent storage

Junit Test Class

Here is the below Junit class to show how to mock ObjectMapper.readValue() using Junit Mockito.

Here we mock ObjectMapper class and notice how we mocked the readValue() method to return UserDto instance.

public class ObjectMapperServiceImplTest {
    private ObjectMapper objectMapper;
    private final ObjectMapperServiceImpl objectMapperServiceImpl = new ObjectMapperServiceImpl();
    public void setUp() {
    public void testUpdateUser() throws Exception {
        UserDto userDto = new UserDto();
        userDto.setName("Soumitra Roy");
        Mockito.when(objectMapper.readValue(Mockito.anyString(), Mockito.any(Class.class))).thenReturn(userDto);
        Mockito.verify(objectMapperServiceImpl, Mockito.times(1)).updateUser();

You may read why you see Mockito.verify() in the above Junit class in this example.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *