Search code examples
javajunitjacksoncode-coverageeclemma

Junit test - Eclemma Coverage in Jackson toString


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?


Solution

  • 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:

    1. Transfer the creation of ObjectMapper to a new method 'getObjectMapper'. During runtime it will decide if it returns a real or a fake mapper.
    2. In your test inject a fake ObjectMapper and make 'getObjectMapper' return the fake mapper instead of a new mapper.
    3. When the writeValueAsString method is called make it throw a JsonProcessingException
    4. Run your test

    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".