Search code examples
javajunitjacksonmockito

Create a JsonProcessingException


I'm trying to create a JsonProcessingException to be thrown by a mock object.

when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error"));

However I'm unable to create a JsonProcessingException object as all the constructors are protected. How do I get around this?


Solution

  • how about you create an anonymous exception of type JsonProcessingException

    when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error"){});
    

    The {} braces does the trick. This is much better since it is not confusing to the reader of the test code.