<code class="java">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); } }</code>>>
本示例演示了基本的平等檢查和局部平等檢查,並使用JSONUNIN的忽略機制進行了局部平等檢查,並顯示瞭如何與ASSERTJ相結合以增強可讀性和錯誤報告。 請記住,將必要的依賴項包含在您的pom.xml
>(或同等的構建文件)中。
JsonAssert.assertEquals()
利用JSONUNIT進行JSON特定比較:assertThat()
>使用jsonunit'swhen()
when()
>在用jsonunit和assertj? JsonAssert.assertNodeEquals()
以上是jsonunit assertj json單元測試示例的詳細內容。更多資訊請關注PHP中文網其他相關文章!