Create a JsonProcessingException
I came across this issue today also. The simplest and cleanest solution I came up with was to create and throw a mock JsonProcessingException
when(mapper.writeValueAsString(any(Object.class)))
.thenThrow(mock(JsonProcessingException.class));
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());
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.