import org.assertj.core.api.Assertions; import net.javacrumbs.jsonunit.JsonAssert; import org.json.JSONObject; import org.junit.jupiter.api.Test; public class JsonUnitTestExample { @Test void testJsonEquality() { String expectedJson = "{\"name\":\"John Doe\",\"age\":30,\"city\":\"New York\"}"; String actualJson = "{\"age\":30,\"city\":\"New York\",\"name\":\"John Doe\"}"; JsonAssert.assertEquals(expectedJson, actualJson); //Order doesn't matter with JsonUnit //Alternatively, using AssertJ for more descriptive failure messages: Assertions.assertThat(JsonAssert.jsonObject(expectedJson)).isEqualTo(JsonAssert.jsonObject(actualJson)); } @Test void testJsonPartialEquality() { String expectedJson = "{\"name\":\"John Doe\",\"age\":30,\"city\":\"New York\",\"country\":\"USA\"}"; String actualJson = "{\"name\":\"John Doe\",\"age\":30}"; // Using JsonUnit's ignoring strategy JsonAssert.assertEquals(expectedJson, actualJson, (node1, node2) -> node1.getNodeName().equals("country")); // Alternatively, using AssertJ with JsonUnit's ignoring functionality within a custom comparator // This gives more control and potentially better error messages Assertions.assertThat(JsonAssert.jsonObject(actualJson)).usingComparator(JsonAssert.when( (node1, node2) -> node1.getNodeName().equals("country") )).isEqualTo(JsonAssert.jsonObject(expectedJson)); } @Test void testJsonWithAssertJAssertions(){ JSONObject expectedJson = new JSONObject("{\"name\":\"John Doe\",\"age\":30}"); JSONObject actualJson = new JSONObject("{\"name\":\"John Doe\",\"age\":30}"); Assertions.assertThat(JsonAssert.jsonObject(actualJson).toString()).isEqualTo(expectedJson.toString()); // Or using JsonUnit's direct comparison JsonAssert.assertEquals(expectedJson, actualJson); } }
本示例演示了基本的平等检查和局部平等检查,并使用JSONUNIN的忽略机制进行了局部平等检查,并显示了如何与ASSERTJ相结合以增强可读性和错误报告。 请记住,将必要的依赖项包含在您的pom.xml
>(或同等的构建文件)中。
JsonAssert.assertEquals()
利用JSONUNIT进行JSON特定比较:assertThat()
>使用jsonunit'swhen()
when()
>在用jsonunit和assertj?JsonAssert.assertNodeEquals()
以上是jsonunit assertj json单元测试示例的详细内容。更多信息请关注PHP中文网其他相关文章!