skyscreamer / JSONassert

Write JSON unit tests in less code. Great for testing REST interfaces.
http://jsonassert.skyscreamer.org
Apache License 2.0
992 stars 197 forks source link

Customization is failling for nested objects #173

Closed rubainwabo closed 1 year ago

rubainwabo commented 1 year ago

I am currently using JSONassert in a project, I would like to ignore some fields using customization like in this example but it doesn't work

String expected = "{\"tasks\":{\"items\":[{\"taskId\":\"55\"},{\"taskId\":\"57\"}]}}";
String actual = "{\"tasks\":{\"items\":[{\"taskId\":\"56\"},{\"taskId\":\"58\"}]}}";

List<Customization> customizations = new ArrayList<>();
customizations.add(new Customization("tasks.items[*].taskId", (o1, o2) -> true));

JSONComparator comparator = new CustomComparator(
        JSONCompareMode.LENIENT,
        customizations.toArray(new Customization[0])
);

JSONAssert.assertEquals(expected, actual, comparator);

Error received :


Expected: a JSON object
     but none found
 ; tasks.items[taskId=57]
Expected: a JSON object
     but none found
 ; tasks.items[taskId=56]
Unexpected: a JSON object
 ; tasks.items[taskId=58]
Unexpected: a JSON object
rubainwabo commented 1 year ago

According to this answer : https://github.com/skyscreamer/JSONassert/issues/117

this issue can be solved by using nested matching. This works for me

        String expected = "{\"tasks\":{\"items\":[{\"taskId\":\"55\"}, {\"taskType\":\"momo\"}]}}";
        String actual = "{\"tasks\":{\"items\":[{\"taskId\":\"56\"}, {\"taskType\":\"momi\"}]}}";

        JSONComparator comparator = new CustomComparator(
                JSONCompareMode.LENIENT,
                new Customization("tasks.items",
                        new ArrayValueMatcher<>(new CustomComparator(
                                JSONCompareMode.LENIENT,
                                new Customization("**.taskId", (o1, o2) -> true)
                        )))
        );

        JSONAssert.assertEquals(expected, actual, comparator);

This gives me the following output :

Exception in thread "main" java.lang.AssertionError: tasks.items[1].taskType
Expected: momo
     got: momi

    at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:482)
    at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:464)
    at JsonAssertTest.main(JsonAssertTest.java:24)

which means that the taskId has been ignored.

I can confirm that the library supports complex nested objects but it should be documented accordingly.