The exception is catched inside add(String)
. Therefore JUnit doesn't see it and cannot test it. (JUnit sees only exceptions that are thrown by the add
method.)
How to test it? There is only one side effect of this method that leaks outside of the method: it writes something to System.err
. You can test this using the System Rules library.
But, usually it is bad practice to silently catch exceptions. The caller does not know that an exception occured. I suggest to not catching the exceptions:
void add(String json) throws JsonParseException, JsonMappingException, IOException {
X x = mapper.readValue(json, X.class);
return null;
}
Then your test will work.
You can wrap the exceptions with a runtime exception, if you don't like the throws
in the method's signature.
void add(String json) {
try {
X x = mapper.readValue(json, X.class);
return null;
} catch (JsonParseException e) {
throw new RuntimeException(e);
} catch (JsonMappingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}