How to unit test a custom Jackson JsonSerializer?
Asked Answered
S

3

7

I wrote the following JsonSerializer to let Jackson serialize an array of integers into JSON:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;

public class TalkIdsSerializer extends JsonSerializer<TalkIds> {

    /**
     * Serializes a TalkIds object into the following JSON string:
     * Example: { "talk_ids" : [ 5931, 5930 ] }
     */
    @Override
    public void serialize(TalkIds talkIds, JsonGenerator jsonGenerator, 
        SerializerProvider provider)
            throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeArrayFieldStart(TalkIds.API_DICTIONARY_KEY);
        for (Integer talkId : talkIds.getTalkIds()) {
            jsonGenerator.writeNumber(talkId);
        }
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
    }

}

The class is used here:

@JsonSerialize(using = TalkIdsSerializer.class)
public class TalkIds { /* ...  */ }

I want test the behavior of the serializer and came up with the following:

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import org.junit.Before;
import org.junit.Test;    
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class TalkIdsSerializerTest {

    protected final ArrayList<Integer> TALK_IDS = 
        new ArrayList<>(Arrays.asList(5931, 5930));

    protected TalkIdsSerializer talkIdsSerializer;

    @Before
    public void setup() throws IOException {
        talkIdsSerializer = new TalkIdsSerializer();
    }

    @Test
    public void testSerialize() throws IOException {
        StringWriter stringWriter = new StringWriter();
        JsonGenerator jsonGenerator = 
            new JsonFactory().createGenerator(stringWriter);
        TalkIds talkIds = new TalkIds();
        talkIds.add(TALK_IDS);
        talkIdsSerializer.serialize(talkIds, jsonGenerator, null);
        String string = stringWriter.toString(); // string is ""
        assertNotNull(string);
        assertTrue(string.length() > 0);
        stringWriter.close();
    }

}

However, nothing is written to the StringWriter. What am I doing wrong?

Saskatoon answered 24/11, 2015 at 11:42 Comment(0)
E
6

You need to flush() the generator

Method called to flush any buffered content to the underlying target (output stream, writer), and to flush the target itself as well.
http://fasterxml.github.io/jackson-core/javadoc/2.1.0/com/fasterxml/jackson/core/JsonGenerator.html#flush()

Eisler answered 24/11, 2015 at 11:50 Comment(1)
https://mcmap.net/q/294021/-how-to-unit-test-jackson-jsonserializer-and-jsondeserializer this answer is more informativePaid
L
2

I had a similar requirement, to test a custom serializer. I used objectMapper to get the string directly(since you have already annotated TalkIds with JsonSerialize). You can get the json string from the object as follows

String json = new ObjectMapper().writeValueAsString(talkIds)
Lula answered 24/11, 2015 at 15:52 Comment(1)
This is by far the easiest method for unit testing JSON serializations. Thanks.Prandial
A
1

For me flush() changed nothing, so I changed the way to test it, in accordance with http://www.baeldung.com/jackson-custom-serialization.

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.StringWriter;

//...

    @Test
    public void serialize_custom() throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(MyCustomSerializer.class, myCustomSerializer);
        objectMapper.registerModule(module);
        StringWriter stringWriter = new StringWriter();

        TalkIds talkIds = new TalkIds();
        talkIds.add(TALK_IDS);

        objectMapper.writeValue(stringWriter,wi);
        assertTrue(stringWriter.toString().length() > 3);
    }
Apish answered 24/3, 2016 at 8:13 Comment(1)
Feel free to checkout the code. Please mind that the API is currently offline. I might mock API responses in order to let testThatRealServerIsReachable() pass again.Saskatoon

© 2022 - 2024 — McMap. All rights reserved.