简体   繁体   English

如何为自定义Jackson Serializer编写JUnit-Test?

[英]How can I write a JUnit-Test for custom Jackson Serializer?

I wanted to test my serializer which parses my java object to a json object. 我想测试我的序列化程序,它将我的java对象解析为json对象。 This is my Serializer class: 这是我的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());
        }
    }

}

My test looks like this: 我的测试看起来像这样:

    @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
        }

So how can I test my serializer? 那么如何测试我的序列化器呢? I tried other answers to similar questions, but nothing worked for me. 我尝试了类似问题的其他答案,但没有任何对我有用。

I use the serializer like this in my other clases: 我在其他文章中使用这样的序列化器:

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

Ok thank you for your answers. 好的,谢谢你的回答。 I got it now this way and it works fine: 我现在用这种方式得到它并且它工作正常:

I changed my serializer a little bit: 我稍微更改了序列化程序:

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

And here are my two tests: 这是我的两个测试:

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");
    }
}

Something like this: 像这样的东西:

@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("{}");
}

This can be achieved by creating a custom JsonGenerator that stores what is written to it. 这可以通过创建一个存储写入内容的自定义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();
    }

}

Then you verify the generated content, without needing to check all the calls to writeString that were made: 然后验证生成的内容,而无需检查所有对writeString的调用:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM