javajacksonassertjjsonnode

Assertj not working with Jackson JsonNode


I'm using assertj and Jackson's JsonNode combined. So far I've been using Assertions.assertThat(objectNode0).isEqualTo(objectNode1); and everything works fine.

Now, I need to ignore some fields in the comparison, and the way I tried is by using usingRecursiveComparison, but it fails to alert when objects are different. Is there any way to overcome this? Here's my sample code:

public class Main {

public static void main(String[] args) {
    ObjectMapper om = new ObjectMapper();

    try {
        JsonNode objectNode0 = om.readTree("{\"someNotImportantValue\":1,\"importantValue\":\"10\"}");
        JsonNode objectNode1 = om.readTree("{\"someNotImportantValue\":15,\"importantValue\":\"1\"}");

        boolean equals = objectNode0.equals(objectNode1);
        System.out.println(equals); // prints false

        //This works, but does not enable to ignore any field
        //Assertions.assertThat(objectNode0).isEqualTo(objectNode1);

        //We would expect this sentence to fail, since importantValue is still different, but it does not.
        Assertions.assertThat(objectNode0).usingRecursiveComparison().ignoringFields("someNotImportantValue").isEqualTo(objectNode1);

    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

}


Solution

  • JsonUnit is usually a better candidate for JSON related assertions and is also integrated with AssertJ.

    With the original example, the following assertion:

    assertThatJson(objectNode0).isEqualTo(objectNode1);
    

    would fail with:

    net.javacrumbs.jsonunit.core.internal.Opentest4jExceptionFactory$JsonAssertError: JSON documents are different:
    Different value found in node "importantValue", expected: <"1"> but was: <"10">.
    Different value found in node "someNotImportantValue", expected: <15> but was: <1>.
    

    However, I would expect also AssertJ with recursive comparison to fail, therefore I raised https://github.com/assertj/assertj-core/issues/2459.