I want to write an unit test to test a JsonProcessingException. This exception can happen on the line: mapper.writeValueAsString().
public void myMethod(Args...) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
Document.parse(mapper.writeValueAsString(testObject)));
}
} catch (JsonProcessingException e) {
log.error("Error parsing the object to json string. ", e);
}
}
and here is my unit test:
public class Test {
@Mock
private ObjectMapper mapper;
@InjectMocks
ClassUnderTest sut;
@Test
public void testJsonProcessingException() throws JsonProcessingException {
when(mapper.writeValueAsString(Mockito.any())).thenThrow(new JsonProcessingException("Error parsing the object to json string. "){
private static final long serialVersionUID = 1L;});
sut.myMethod(args...);
}
}
The problem is the mapper which i have mocked will not be used (i get unnecessary Mockito stubbings failure) as the mapper is again initialized inside the method. How can i unit test such a situation with mockito?