1

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?

ruhungry
  • 4,506
  • 20
  • 54
  • 98

1 Answers1

1

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);
  }
}
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
  • It seems strange that I need to change my code to test it. I want to keep it in this shape and write test. Seriously, it is not possible? – ruhungry Feb 14 '14 at 08:42
  • 1
    As I told before. Your code writes to System.err and you can test this using the System Rules library. Should I add an example? – Stefan Birkner Feb 14 '14 at 09:30
  • Sorry, I focused on another part of your message. I will try it. – ruhungry Feb 14 '14 at 13:42