Search code examples
javajunitjacksonjson-deserializationjackson-databind

How to prepare or mock JsonParser to test custom StdDeserializer


I have custom StdDeserializer<Date>, how can i unit test the overridden deserialize method here?

or how can i prepare or mock JsonParser here for unit testing desterilize method?

public class StringToDateDeserializer extends StdDeserializer<Date> {

    protected StdDateFormat df = new StdDateFormat();

    public StringToDateDeserializer() {
        this(null);
    }

    protected StringToDateDeserializer(Class<?> T) {
        super(T);
    }

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
        String dateStr = jsonParser.getText();
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        try {
            return df.parse(dateStr);
        } catch (ParseException e) {
            throw new MyCustomException("Invalid date passed, ISO 8601 is expected");
        }
    }
}

Solution

  • Example of test for StringToDateDeserializer with 100% coverage.

    public class TestClass {
        private ObjectMapper mapper;
        private StringToDateDeserializer deserializer;
    
        @Before
        public void setup() {
            mapper = new ObjectMapper();
            deserializer = new StringToDateDeserializer();
        }
    
        @Test
        public void dateTest() throws IOException {
            Date date = deserializer.deserialize(prepareParser("{ \"value\":\"2020-07-10T15:00:00.000\" }"), mapper.getDeserializationContext());
    
            Assert.assertNotNull(date);
            Assert.assertEquals(1594393200000L, date.getTime());
        }
    
        @Test(expected = MyCustomException.class)
        public void exceptionalTest() throws IOException {
            deserializer.deserialize(prepareParser("{ \"value\":\"2020-07\" }"), mapper.getDeserializationContext());
        }
    
        @Test
        public void nullTest() throws IOException {
            Date date = deserializer.deserialize(prepareParser("{ \"value\":\"\" }"), mapper.getDeserializationContext());
    
            Assert.assertNull(date);
        }
    
        private JsonParser prepareParser(String json) throws IOException {
            JsonParser parser = mapper.getFactory().createParser(json);
            while (parser.nextToken() != JsonToken.VALUE_STRING);
            return parser;
        }
    }