我为我的应用编写了自定义JsonSerializer和JsonDeserializer。 现在我想为它们编写一些单元测试。
干净的测试用例应该如何?
那里有一些干净的例子吗?
(clean表示不依赖于其他框架或库)
答案 0 :(得分:37)
<强> JsonSerializer 强>
示例是序列化LocalDateTime
,但这可以替换为所需类型。
@Test
public void serialises_LocalDateTime() throws JsonProcessingException, IOException {
Writer jsonWriter = new StringWriter();
JsonGenerator jsonGenerator = new JsonFactory().createGenerator(jsonWriter);
SerializerProvider serializerProvider = new ObjectMapper().getSerializerProvider();
new LocalDateTimeJsonSerializer().serialize(LocalDateTime.of(2000, Month.JANUARY, 1, 0, 0), jsonGenerator, serializerProvider);
jsonGenerator.flush();
assertThat(jsonWriter.toString(), is(equalTo("\"2000-01-01T00:00:00\"")));
}
<强> JsonDeserializer 强>
示例是对Number
进行反序列化,但这可以替换为所需的类型。
private ObjectMapper mapper;
private CustomerNumberDeserialiser deserializer;
@Before
public void setup() {
mapper = new ObjectMapper();
deserializer = new CustomerNumberDeserialiser();
}
@Test
public void floating_point_string_deserialises_to_Double_value() {
String json = String.format("{\"value\":%s}", "\"1.1\"");
Number deserialisedNumber = deserialiseNumber(json);
assertThat(deserialisedNumber, instanceOf(Double.class));
assertThat(deserialisedNumber, is(equalTo(1.1d)));
}
@SneakyThrows({JsonParseException.class, IOException.class})
private Number deserialiseNumber(String json) {
InputStream stream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
JsonParser parser = mapper.getFactory().createParser(stream);
DeserializationContext ctxt = mapper.getDeserializationContext();
parser.nextToken();
parser.nextToken();
parser.nextToken();
return deserializer.deserialize(parser, ctxt);
}
<强>更新强>
升级到jackson 2.9.3时,在将字符串反序列化为数字时,我在NullPointerException
的{{1}}收到了DeserializationContext
,因为isEnabled(MapperFeature feature)
将new ObjectMapper()
初始化为_config
1}}。
为了解决这个问题,我使用this SO回答来监视null
班级final
:
DeserializationContext
我觉得必须有一个更好的方法,所以如果你有一个,请发表评论。
答案 1 :(得分:6)
解串器可以像这样进行单元测试:
public class CustomFooDeserializerTest {
private Foo foo;
@Before
public void setUp() {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Foo.class, new CustomFooDeserializer());
objectMapper.registerModule(module);
foo = objectMapper.readValue(new File("path/to/file"), Foo.class);
}
@Test
public void shouldSetSomeProperty() {
assertThat(foo.getSomeProperty(), is("valueOfSomeProperty"));
}
}
答案 2 :(得分:4)
其他答案很好地涵盖了序列化。对于反序列化,我还有其他建议。
如果您的域类具有@JsonDeserialize
批注,则默认的ObjectMapper将使用反序列化器,而无需显式注册它。
@JsonDeserialize(using=ExampleDeserializer.class)
public class Example {
private String name;
private BananaStore bananaStore;
public Example(String name, BananaStore bananaStore) {
this.name = name;
this.bananaStore = bananaStore;
}
public String getName() {
return name;
}
public BananaStore getBananaStore() {
return bananaStore;
}
}
并且您的单元测试可以变得更短:
public class ExampleDeserializerTest {
@Test
public void deserialize() throws IOException {
String json = "{\"name\":\"joe\",\"bananas\":16}";
Example example = new ObjectMapper().readValue(json, Example.class);
assertEquals("joe", example.getName());
assertEquals(16, example.getBananaStore().getBananaCount());
}
}
答案 3 :(得分:3)
我找到了一种对反序列化器进行单元测试的方法,很难搞清楚。看看我的回购https://bitbucket.org/arbeitsgruppedenktmit/de.denktmit.rest.hal
单元测试课在这里: de.denktmit.rest.hal / src / test / java / de / denktmit / rest / hal / jackson / RelationDeserializerTest.java
可以在此处找到用于在上下文中测试反序列化器的集成测试: de.denktmit.rest.hal / src / test / java / de / denktmit / rest / hal / OrderResourceIntegrationTest.java
由于评论而编辑 用于设置映射器以便于单元测试的基类
public abstract class AbstractJackson2MarshallingTest {
protected ObjectMapper mapper;
@Before
public void setUp() {
mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
}
protected String write(Object object) throws Exception {
Writer writer = new StringWriter();
mapper.writeValue(writer, object);
return writer.toString();
}
protected <T> T read(String source, Class<T> targetType) throws Exception {
return mapper.readValue(source, targetType);
}
protected String getPackagePath() {
return "/" + this.getClass().getPackage().getName().replace('.', '/');
}
}
包含单元测试的测试类
public class RelationDeserializerTest extends AbstractJackson2MarshallingIntegrationTest {
@Rule public ResourceFile resourceFile = new ResourceFile(getPackagePath() + "/single_valued_relation.json");
@Rule public ResourceFile resourceFile2 = new ResourceFile(getPackagePath() + "/multi_valued_relation.json");
private RelationDeserializer deserializer = new RelationDeserializer();
@Test
public void testDeserializeSingleValuedRelation() throws IOException {
resourceFile = new ResourceFile(getPackagePath() + "/single_valued_relation.json");
JsonParser parser = mapper.getFactory().createParser(resourceFile.getContent());
DeserializationContext ctxt = mapper.getDeserializationContext();
SingleValuedRelation rel = (SingleValuedRelation) deserializer.deserialize(parser, ctxt);
assertEquals(rel.getName(), "invoiceAddress");
assertEquals("invoiceAddressURL", rel.getLink().getHref());
assertEquals("linkName", rel.getLink().getName());
assertEquals("de", rel.getLink().getHreflang());
assertNull(parser.nextToken());
}
@Test
public void testDeserializeMultiValuedRelation() throws IOException {
resourceFile = new ResourceFile(getPackagePath() + "/multi_valued_relation.json");
JsonParser parser = mapper.getFactory().createParser(resourceFile.getContent());
DeserializationContext ctxt = mapper.getDeserializationContext();
MultiValuedRelation rel = (MultiValuedRelation) deserializer.deserialize(parser, ctxt);
assertEquals(rel.getName(), "images");
Iterator<Link> linkIterator = rel.getLinks().iterator();
Link link = linkIterator.next();
assertEquals("imageUrl1", link.getHref());
link = linkIterator.next();
assertEquals("imageUrl2", link.getHref());
assertNull(parser.nextToken());
}
}
受测试的课程
public class RelationDeserializer extends StdDeserializer<Relation> {
public RelationDeserializer() {
super(Relation.class);
}
@Override
public Relation deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
if (p.getCurrentToken() == null && p.nextToken() == null) {
String msg = getClass().getCanonicalName()
+ ": Can not deserialize without token";
throw new IOException(msg);
}
if (p.getCurrentToken() != JsonToken.START_OBJECT
&& p.getCurrentToken() != JsonToken.START_ARRAY) {
String msg = getClass().getCanonicalName()
+ ": Expected data to start with an Relation object or an array of Relation objects";
throw new IOException(msg);
}
if (p.nextToken() != JsonToken.FIELD_NAME) {
String msg = getClass().getCanonicalName()
+ ": Expected relation to be started by a field name";
throw new IOException(msg);
}
String relationName = p.getText();
JsonToken tok = p.nextToken();
Relation rel;
switch (tok) {
case START_ARRAY:
rel = createMultiValuedRelation(relationName, p);
break;
case START_OBJECT:
rel = createSingleValuedRelation(relationName, p);
break;
default:
String msg = getClass().getCanonicalName() + "Expected relation content is a single link or array of links";
throw new IOException(msg);
}
p.nextToken();
return rel;
}
private Relation createMultiValuedRelation(String relationName, JsonParser p)
throws JsonParseException, IOException {
List<Link> links = new ArrayList<Link>();
if (p.nextToken() == JsonToken.START_OBJECT) {
Iterator<DefaultLink> linkIterator = p.readValuesAs(DefaultLink.class);
while (linkIterator.hasNext()) {
links.add(linkIterator.next());
}
}
if (p.getCurrentToken() != JsonToken.END_ARRAY) {
String msg = getClass().getCanonicalName() + "Expected relation content is a single link or (possibly empty) array of links";
throw new IOException(msg);
}
return RelationFactory.createRelation(relationName, links);
}
private Relation createSingleValuedRelation(String relationName,
JsonParser p) throws JsonParseException, IOException {
return RelationFactory.createRelation(relationName, p.readValueAs(DefaultLink.class));
}
}
希望有帮助和最好的问候
答案 4 :(得分:2)
我没有找到任何示例,但您可以尝试创建一个生成器,如:
StringWriter stringJson = new StringWriter();
JsonGenerator generator = new JsonFactory().createGenerator(stringJson);
您可以使用
获取SerializerProvider
个实例
new ObjectMapper().getSerializerProvider();
答案 5 :(得分:0)
我开始在@RobertBain的答案中使用该解决方案,但由于JSON解析器一直以某种方式失去了该值,因此它对我不起作用。我最终加入了Mockito,并在反序列化器使用的JsonParser
上添加了方法,并使用该方法编写了测试。请参见下面的一个小示例:
public class ZoneDateTimeDeserializerTest {
private ZoneDateTimeDeserializer deserializer;
@Mock
private JsonParser parser;
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Before
public void setUp() {
deserializer = new ZoneDateTimeDeserializer();
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
@Test
public void givenAZonedDateTimeInIsoFormat_whenTryingToDeserializeIt_itShouldBeSuccessful() {
final String date = "1996-01-29T22:40:54+02:00";
ZonedDateTime dateTime = deserialiseZoneDateTime(date);
Assert.assertNotNull(dateTime);
assertThat(dateTime, instanceOf(ZonedDateTime.class));
Assert.assertEquals(1996, dateTime.getYear());
Assert.assertEquals(Month.JANUARY, dateTime.getMonth());
Assert.assertEquals(29, dateTime.getDayOfMonth());
Assert.assertEquals(20, dateTime.getHour());
Assert.assertEquals(40, dateTime.getMinute());
Assert.assertEquals(54, dateTime.getSecond());
}
@SneakyThrows({JsonParseException.class, IOException.class})
private ZonedDateTime deserialiseZoneDateTime(String json) {
// Mock the parser so that it returns the value when getValueAsString is called on it
when(parser.getValueAsString()).thenReturn(json);
return deserializer.deserialize(parser, null);
}
}