我想测试将我的java对象解析为json对象的序列化器。这是我的序列化器类:
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;
好的,谢谢您的回答。我现在以这种方式得到它,并且工作正常:
我稍微改变了序列化器:
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");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句