I have the following method. The method converts the contents of a json string by using the Jackson ObjectMapper. If the json is malformed the stack trace is printed and the object is set to null:
public ObjectTransferData extractJacksonObjectsFromFile(String json) {
ObjectTransferData objectTransferData;
try {
objectTransferData = objectMapper.readValue(json, ObjectTransferData.class);
} catch (Exception e) {
e.printStackTrace();
objectTransferData = null;
}
return objectTransferData;
}
I wrote the JUnit unit test for a possible malformed json string like this:
@Test
public void testExtractJacksonObjectsFromFile_malformedJson_expectNull(){
String malformedJson = "{";
ObjectTransferData result = myService.extractJacksonObjectsFromFile(malformedJson);
assertNull(result);
}
This test passes. But it is also printing the e.printStackTrace()
into my terminal which is obscuring the actual important logs during test execution. It can be confusing for the reader of the test execution.
I am wondering how to resolve this issue. I came up with these ideas:
- Remove the try/catch and just throw the exception. This would allow me to just write the test like this and not get a stacktrace into the console.
@Test
public void testExtractJacksonObjectsFromFile_malformedJson_expectException(){
String malformedJson = "{";
assertThrows(Exception.class, () ->
objectImportService.extractJacksonObjectsFromFile(malformedJson)
);
}
However the disadvantage is that the real application now throws this Exception and does not gracefully fail by handling it through a catch block.
- Somehow suppress the exception logging for the tests. But this could lead to supressed logs for actual errors during the test execution.
This question is somewhat related, but does not fully answer my question. I could just redirect all testing stacktraces to a file like this, but I don't want to redirect actual exceptions during test execution. Telling a specific test to not print stacktrace would be ideal.