如何为自定义的Jackson序列化器编写JUnit测试?

3

我想要测试我的序列化程序,它能够将Java对象解析为JSON对象。这是我的Serializer类:

public class CountryCodeSerializer extends JsonSerializer<CountryCode> {

    @Override
    public void serialize(CountryCode value, JsonGenerator generator, SerializerProvider provider)
            throws IOException, JsonProcessingException {

        if (value == null) {
            generator.writeString("{}");
        } else {
            generator.writeString(value.toString());
        }
    }

}

我的测试看起来是这样的:

    @Before
        public void setUp() throws Exception {
            stringJson = new StringWriter();
            generator = new JsonFactory().createGenerator(stringJson);
            provider = new ObjectMapper().getSerializerProvider();
            countryCode = CountryCode.parse("us");
        }

        @Test
        public void parsingNullReturnsNull() throws Exception {
            assertThat(countryCodeSerializer.serialize(countryCode, generator, provider)).isEqualTo("{'countrycode':'us'}); //this doesn't work, since serialize() is void

//countryCodeSerializer.serialize(countryCode, generator, provider); //this throws an java.lang.NullPointerException
        }

那么我该如何测试我的序列化器?我尝试了其他类似问题的答案,但都没有起作用。

在我的其他类中,我像这样使用序列化器:

@JsonSerialize(using = CountryCodeSerializer.class)
    private CountryCode countryCode;

也许你应该模拟JsonGenerator并验证是否将正确的内容写入其中。 - andrucz
3个回答

1

好的,谢谢你的回答。我现在这样做了,它可以正常工作:

我稍微改了一下我的序列化器:

public class CountryCodeSerializer extends JsonSerializer<CountryCode> {
       @Override
        public void serialize(CountryCode value, JsonGenerator generator, SerializerProvider provider)
                throws IOException, JsonProcessingException {

            if (null == value) {
                throw new IllegalArgumentException("CountryCode is null");
            } else {
                generator.writeString(value.toString());
            }
        }        
    }

这里是我的两个测试:

public class CountryCodeSerializerTest {

    private CountryCodeSerializer countryCodeSerializer;
    private JsonGenerator jsonGenerator;

    @Before
    public void setUp() throws Exception {
        countryCodeSerializer = new CountryCodeSerializer();
        jsonGenerator = mock(JsonGenerator.class);
    }

    @Test
    public void testNullCountryCodeThrowsIllegalArgumentException() throws Exception {
        try {
            countryCodeSerializer.serialize(null, jsonGenerator, null);
            fail("An IllegalArgumentException should have been thrown.");
        } catch (IllegalArgumentException e) {
            //ok
        }
    }

    @Test
    public void testCountryCodeConvertedToJsonString() throws Exception {
        countryCodeSerializer.serialize(CountryCode.parse("us"), jsonGenerator, null);
        verify(jsonGenerator).writeString("us");
    }
}

0

类似这样:

@Mock 
private JsonGenerator generator;

@Test
public void testInstanceWithValue() {
    //SETUP
    String expectedValue = "test value";
    CountryCode value = mock(CountryCode.class);
    when(value.toString()).thenReturn(expectedValue);

    // CALL
    CountryCodeSerializer instance = new CountryCodeSerializer(value, generator, null);

    // VERIFY
    verify(generator).writeString(expectedValue);
}

@Test
public void testInstanceWithNull() {
    //SETUP
    CountryCode value = null;

    // CALL
    CountryCodeSerializer instance = new CountryCodeSerializer(value, generator, null);

    // VERIFY
    verify(generator).writeString("{}");
}

0
这可以通过创建一个自定义的JsonGenerator来实现,该生成器会存储写入其中的内容。
class TestJsonGenerator extends JsonGenerator {

    private StringBuilder stringBuilder = new StringBuilder();

    ...

    @Override
    public void writeString(String text) {
        stringBuilder.append(text);
    }

    public String getText() {
        return stringBuilder.toString();
    }

}

然后您可以验证生成的内容,而无需检查所有调用 writeString 的情况:

TestJsonGenerator testGenerator = new TestJsonGenerator();
serializer.serialize(countryCode, testGenerator, provider);

assertThat(testGenerator.getText()).isEqualsTo("{ \"foo\": \"bar\" }");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接