Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 289
pez Avatar asked May 27 '15 06:05

pez


5 Answers

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.

like image 118
rajan.jana Avatar answered Nov 13 '22 12:11

rajan.jana


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
like image 19
Jose Martinez Avatar answered Nov 13 '22 12:11

Jose Martinez


This one worked for me which allowed to throw JsonProcessingException itself

doThrow(JsonProcessingException.class).when(mockedObjectMapper).writeValueAsString(Mockito.any());
like image 11
Albin Avatar answered Nov 13 '22 13:11

Albin


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));
like image 6
Aaron McGhie Avatar answered Nov 13 '22 12:11

Aaron McGhie


Faced the same issue today. You can use:

Mockito.when(mockObjectMapper.writeValueAsString(Mockito.any())).thenThrow(JsonProcessingException.class);
like image 3
StoneCold Avatar answered Nov 13 '22 14:11

StoneCold