Pal*_*Dot 1 java junit mockito jackson junit5
我有下面的 Junit.i 正在尝试测试比较两个 Json 字符串是否具有相同的字段(顺序和值并不重要)。我的测试不断失败并出现以下错误
org.opentest4j.AssertionFailedError:预期:<{“person_id”:0,“person_name”:null}>但是:<{“person_id”:0,“person_name”:null}
@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);
}
Run Code Online (Sandbox Code Playgroud)
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 ;
Run Code Online (Sandbox Code Playgroud)
我建议根本不要使用原始字符串比较(因为它是在 JUnit 内部完成的assertEquals)。
相反,您应该使用一个在逻辑级别上比较预期 JSON 和实际 JSON 的库(即忽略空格和属性序列)。有关更多信息,请参阅jsonassert.skyscreamer.org和Baeldung - JSONassert 简介。
使用此库,您可以比较两个 JSON 字符串,而不是通过
assertEquals(bean, jsonString, true);
Run Code Online (Sandbox Code Playgroud)
但相反
JSONAssert.assertEquals(bean, jsonString, true);
Run Code Online (Sandbox Code Playgroud)
然后,只有在存在“真正”差异的情况下,您才会收到断言错误。
| 归档时间: |
|
| 查看次数: |
5873 次 |
| 最近记录: |