I want to have 100% coverage on the method toString overriden with Jackson JSON.
@Override
public String toString() {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
logger.error(e.getMessage());
return "";
}
}
I can make a test that can coverage the most of the code except the catch block.
@Test
public void testToString() {
TestClass testClass = new TestClass();
String expected = "{\"testAttr\":null}";
assertEquals(expected, testClass.toString());
}
How could I make a test that covers the catch block?
Of course you cold try to trigger that exception somehow with setting the enclosing object to some weird kind of state. But a better way to achieve full code coverage is mocking the mapper and making it throw the desired exception. Generally the steps that you need are:
In theory you could manually create the fake ObjectMapper e.g. by creating a subclass of it but that's not the recommended way. I would recommend using a mocking framework. A mocking framework lets you express things like "when method A is called then throw exception B".