ホームページ >Java >&#&チュートリアル >jsonunit assertj jsonユニットテストの例
このセクションは、JavaでのJSONユニットテストのためにJsonunitとAssertjを一緒に使用する方法を示す具体的な例を提供します。 AssertJのFluent Assortions for ReadabilityとJSON比較を処理するためのJsonunitの機能を活用します。 必要な依存関係を
(または同等のビルドファイル)に含めることを忘れないでください。 ASSERTJは、アサーション用の流fluentで読みやすいAPIを提供します。 それらを組み合わせると、両方のライブラリの強度が活用されます。 効果的な使用には、JSON固有の比較のためにjsonunitをレバレッジする<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>
pom.xml
jsonunit:
JSON構造全体またはその部分を比較するためにJsonAssert.assertEquals()
assertThat()
jsonunitのさまざまなアサーション方法を採用しています。実行、およびアサーションフェーズ。以上がjsonunit assertj jsonユニットテストの例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。