我想测试我的序列化器,它将我的java对象解析为一个json对象。这是我的序列化器类:如何为定制Jackson序列化程序编写JUnit测试?
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
}
因此,如何能测试我的串行器?我尝试了类似问题的其他答案,但没有为我工作。
我这样使用串行我在其他clases:
@JsonSerialize(using = CountryCodeSerializer.class)
private CountryCode countryCode;
也许你应该嘲笑JsonGenerator和验证是否写入正确的内容。 – andrucz