gpt4 book ai didi

java - 如何准备或模拟 JsonParser 以测试自定义 StdDeserializer

转载 作者:行者123 更新时间:2023-12-05 04:26:26 24 4
gpt4 key购买 nike

我有自定义 StdDeserializer<Date> ,我如何对重写的 deserialize 进行单元测试方法在这里?

或者我如何准备或模拟 JsonParser在这里进行单元测试除菌方法?

public class StringToDateDeserializer extends StdDeserializer<Date> {

protected StdDateFormat df = new StdDateFormat();

public StringToDateDeserializer() {
this(null);
}

protected StringToDateDeserializer(Class<?> T) {
super(T);
}

@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
String dateStr = jsonParser.getText();
if (StringUtils.isEmpty(dateStr)) {
return null;
}
try {
return df.parse(dateStr);
} catch (ParseException e) {
throw new MyCustomException("Invalid date passed, ISO 8601 is expected");
}
}
}

最佳答案

StringToDateDeserializer 的测试示例,覆盖率为 100%。

public class TestClass {
private ObjectMapper mapper;
private StringToDateDeserializer deserializer;

@Before
public void setup() {
mapper = new ObjectMapper();
deserializer = new StringToDateDeserializer();
}

@Test
public void dateTest() throws IOException {
Date date = deserializer.deserialize(prepareParser("{ \"value\":\"2020-07-10T15:00:00.000\" }"), mapper.getDeserializationContext());

Assert.assertNotNull(date);
Assert.assertEquals(1594393200000L, date.getTime());
}

@Test(expected = MyCustomException.class)
public void exceptionalTest() throws IOException {
deserializer.deserialize(prepareParser("{ \"value\":\"2020-07\" }"), mapper.getDeserializationContext());
}

@Test
public void nullTest() throws IOException {
Date date = deserializer.deserialize(prepareParser("{ \"value\":\"\" }"), mapper.getDeserializationContext());

Assert.assertNull(date);
}

private JsonParser prepareParser(String json) throws IOException {
JsonParser parser = mapper.getFactory().createParser(json);
while (parser.nextToken() != JsonToken.VALUE_STRING);
return parser;
}
}

关于java - 如何准备或模拟 JsonParser 以测试自定义 StdDeserializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73053093/

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