我想要测试我的序列化程序,它能够将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;