Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a JsonProcessingException using Jackson

Tags:

java

json

jackson

Might be a strange question but indeed I would like to achieve a a bit more coverage on my tests and although I coded against a JsonProcessingException I can't create a payload that generates this exception, maybe because Jackson is quite smart and converts everything to a string, and even for bad strings it goes around the JSON specs. My problem is that Jackson is quite good :)

I basically want a payload that when I run this, it break with JsonProcessingException:

String jsonPayload = objectMapper.writeValueAsString(payload); 

I've tried some like:

HashMap<String, String> invalidJSONPayload= new HashMap<>();  invalidJSONPayload.put("021",021); invalidJSONPayload.put("---",021); invalidJSONPayload.put("~",021); 

I'm not fussed with the type, so feel free to suggest another one. An empty object for example, throws JsonMappingException and I already catch that one as well.

like image 889
bitoiu Avatar asked Nov 03 '14 14:11

bitoiu


People also ask

When we will get JsonProcessingException?

You can get a JsonProcessingException if mapping two fields to the same property. Exception message is "Multiple fields representing property "s":..."

What is a JsonProcessingException?

public class JsonProcessingException extends IOException. Intermediate base class for all problems encountered when processing (parsing, generating) JSON content that are not pure I/O problems. Regular IOException s will be passed through as is. Sub-class of IOException for convenience.


1 Answers

I wanted to do the same thing, and eventually accomplished it by using the Mockito "spy" function, which wraps a real object with a mock object. All calls to the mock object get forwarded to the real object, except those you are trying to mock. For example:

ObjectMapper om = Mockito.spy(new ObjectMapper()); Mockito.when( om.writeValueAsString(ErrorObject.class)).thenThrow(new JsonProcessingException("") {}); 

All usages of om will be handled by the underlying ObjectMapper instance until an instance of ErrorObject gets passed in, at which point the JsonProcessingException will be thrown.

The newJsonProcessingException is created as an anonymous class, as it is a protected class and only a sub-class can be instantiated.

like image 147
Lee Passey Avatar answered Sep 29 '22 01:09

Lee Passey