Throw a JsonProcessingException

I am trying to throw a JsonProcessingException that will be thrown by a mock object.

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

However, I cannot create a JsonProcessingException object, since all the constructors are protected. How do I get around this?

+17
source share
4 answers

how about throwing an anonymous exception like JsonProcessingException

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

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

+20
source

How about throwing one of the famous direct subclasses?

for v1.0

 Direct Known Subclasses: JsonGenerationException, JsonMappingException, JsonParseException 

for v2.0

 Direct Known Subclasses: JsonGenerationException, JsonParseException 
+16
source

This worked for me, which allowed a JsonProcessingException to be thrown

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

Try using thenAnswer and create an anonymous class from JsonProcessingException

 when(mapper.writeValueAsString(any(Object.class))).thenAnswer(x-> {throw new JsonProcessingException(""){};}); 
0
source

Source: https://habr.com/ru/post/987978/


All Articles