【发布时间】:2021-03-10 20:35:37
【问题描述】:
我有下面的 Junit。我正在尝试比较两个 Json 字符串是否具有相同的字段(顺序和值不重要)。我的测试不断失败,出现以下错误
org.opentest4j.AssertionFailedError:预期: 但是是:
@Test
void inputpojo_test() throws Exception {
String path = "src/test/data/json_file.txt";
String jsonString = new String(Files.readAllBytes(Paths.get(path)));
Input i = new Input();
ObjectMapper objectMapper = new ObjectMapper();
String bean =objectMapper.writeValueAsString(i);
assertEquals(bean,jsonString);
}
json_file.txt 是{"person_id":0,"person_name":null},输入类是
@JsonProperty("person_id") //getters and setter ommited for brevity
int id;
@JsonProperty("person_name")
String name ;
@JsonIgnore
String value ;
【问题讨论】:
-
无法保证键值会以相同的顺序写入,因此比较 json 字符串是没有意义的。比较节点,使用
valueToTree和readTree -
标签: java junit jackson mockito junit5