I am trying to unit test catch block to convert List into Json format using jackson. Here is my code:
public String convert(List<POJO> list) {
ObjectMapper objectMapper = new ObjectMapper();
try {
data = objectMapper.writeValueAsString(list);
} catch (JsonProcessingException exception) {
System.out.println("Exception message: {}", exception.getMessage());
}
return data;
}
I tried unit testing this way:
@Mock
ObjectMapper mockObjectMapper;
@Test(expected = JsonProcessingException.class)
public void doThrowException() throws JsonProcessingException {
doThrow(JsonProcessingException.class).when(mockObjectMapper).writeValueAsString(any());
dataTransformer.convert(new ArrayList<>());
verify(mockObjectMapper.writeValueAsString(any()));
}
I have been trying to get my head around to cover this unit test for full coverage. I looked up couple of articles on SO, but no luck. Since I am new to unit testing world, I have a feeling that I am definitely missing something here.