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?
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.
How about throwing one of the known direct subclasses instead?
for v1.0
Direct Known Subclasses:
JsonGenerationException, JsonMappingException, JsonParseException
for v2.0
Direct Known Subclasses:
JsonGenerationException, JsonParseException
This one worked for me which allowed to throw JsonProcessingException itself
doThrow(JsonProcessingException.class).when(mockedObjectMapper).writeValueAsString(Mockito.any());