gpt4 book ai didi

java - 如何为自定义 Jackson Serializer 编写 JUnit 测试?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:54:43 26 4
gpt4 key购买 nike

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

那么我该如何测试我的序列化器呢?我尝试了类似问题的其他答案,但对我没有任何帮助。

我在其他类(class)中使用这样的序列化程序:

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

关于java - 如何为自定义 Jackson Serializer 编写 JUnit 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35725268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com