Assertj 不与 Jackson JsonNode 一起工作

Assertj not working with Jackson JsonNode

我正在结合使用 assertj 和 Jackson 的 JsonNode。到目前为止,我一直在使用 Assertions.assertThat(objectNode0).isEqualTo(objectNode1); 并且一切正常。

现在,我需要在比较中忽略一些字段,我尝试的方法是使用usingRecursiveComparison,但是当对象不同时它会失败。 有什么办法可以克服这个问题吗?这是我的示例代码:

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();
    }
}

}

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

结合原来的例子,断言如下:

assertThatJson(objectNode0).isEqualTo(objectNode1);

会失败:

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>.

但是,我希望递归比较的 AssertJ 也会失败,因此我提出 https://github.com/assertj/assertj-core/issues/2459