Question

I wrote the following code :

    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Test
    public void testMappingException() {


        exception.expect(ArithmeticException.class);

        int x = 1 / 0;
    }

Everything works correctly. Unfortunatelly it is not working correctly in this case:

ObjectMapper mapper = new ObjectMapper();
void add(String json) {

    try {

        X x = mapper.readValue(json, X.class); // exception here

    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

========================================================

@Before
public void setUpBeforeClass() {
    jsonTestExcpetion = "{\"aaa\" : \"bbb\"}";
}


@Test
public void testMappingException() {

    MyClass mc = new MyClass();
    exception.expect(UnrecognizedPropertyException.class);
    myClass.add(jsonTestExcpetion);

}

It should catch the exception

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException

but in fact, exception is thrown normally and tests fails.

Have you got any ideas?

Was it helpful?

Solution

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);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top