1

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?

Godin
  • 9,801
  • 2
  • 39
  • 76
Unai Fifo
  • 13
  • 4

2 Answers2

0

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

FarwoodHill
  • 552
  • 1
  • 9
  • 18
0
  1. You can define some attributes to your class and assert the return of the string.
  2. You've already tested the null object.
  3. Raise the exception and see if it handles it. Like: when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error"){}); And also helpful link
Oguz
  • 1,867
  • 1
  • 17
  • 24