How to unit test a custom Jackson JsonSerializer?

JJD picture JJD · Nov 24, 2015 · Viewed 7.2k times · Source

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?

Answer

Murat Karag&#246;z picture Murat Karagöz · Nov 24, 2015

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()