Skip to content
Advertisement

Mockito:: Unit test case for JsonProcessingException when passing object

I have a class as shown below:

@Getter
@Setter
public class User{

    @Autowired
    Logger log;

    private String name;
    private String age;

    public String toJson(){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = null;
        try{
            jsonString = objectMapper.writeValueAsString(this);
        }catch(JsonProcessingException jsnEx){
            log.writeErr(" Error while parsing the Json" + jsnEx.getMessage());
        }
        return jsonString;
    }
}

Now I am trying to write a unit test case for this where I can throw exception and unit test the catch clause using Mockito but I am not able to mock it. I have noticed that object mapper class internally converting everything to string even if I set name and age to null. Can anyone please help me with this?

Advertisement

Answer

Use constructor injection with Spring. This will allow you to inject mocked ObjectMapper in the class, which then you can set behavior in the test. See below.

@Getter
@Setter
public class User{

    private String name;
    private String age;
    
    private final Logger log;
    private final ObjectMapper objectMapper;
    
    public User(Logger log, ObjectMapper objectMapper){
        this.log = log;
        this.objectMapper = objectMapper;
    }

    public String toJson(){
        String jsonString = null;
        try{
            jsonString = objectMapper.writeValueAsString(this);
        }catch(JsonProcessingException jsnEx){
            log.writeErr(" Error while parsing the Json" + jsnEx.getMessage());
        }
        return jsonString;
    }
}


// Test

@Before
public setup(){
    @Mock
    Logger log;
    
    @Mock
    ObjectMapper objectMapper;        
    testObject = new User(log, objectMapper);
}

@Test
public test_toJson(){
    // given
    when(objectMapper.writeValueAsString(any())).thenThrow(new JsonProcessingException("Fake exception"))
    // when
    testObject.toJson()
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement