0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSONAssertsを用いたJson比較、一部分だけ比較しないメモ

Posted at

JSONAssertsで遊ぶ

import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.CustomComparator;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.comparator.Customization;

public class JsonComparisonTest {

    @Test
    void test_01() throws JSONException {
        // language=json
        String expect = "{ \"time\" : {\n" +
                "  \"insertTime\": \"201912010023\",\n" +
                "  \"updateTime\": \"202008111234\"\n" +
                "},\n" +
                "\"animal\": \"gorilla\"}\n";

        // language=json
        String actual = "{ \"time\" : {\n" +
                "  \"insertTime\": null,\n" +
                "  \"updateTime\": \"999999999999\"\n" +
                "},\n" +
                "\"animal\": \"gorilla\"}\n";

        JSONAssert.assertEquals(expect, actual,
                new CustomComparator(JSONCompareMode.STRICT,
                        new Customization("time.insertTime", (o1, o2) -> {
                            if (o2 == null) return true; // actualがnullの場合は無視
                            if (o1 instanceof String && o2 instanceof String) {
                                return ((String) o2).matches("201912010023"); // 正規表現で比較
                            }
                            return false;
                        }),
                        new Customization("time.updateTime", (o1, o2) -> {
                            if (o2 == null) return true; // actualがnullの場合は無視
                            if (o1 instanceof String && o2 instanceof String) {
                                return ((String) o2).matches(".*"); // 正規表現で比較
                            }
                            return false;
                        })
                )
        );
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?