Create a JsonProcessingException

2019-04-18 13:19发布

问题:

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?

回答1:

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.



回答2:

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


回答3:

This one worked for me which allowed to throw JsonProcessingException itself

doThrow(JsonProcessingException.class).when(mockedObjectMapper).writeValueAsString(Mockito.any());