【问题标题】:Assertj not working with Jackson JsonNodeAssertj 不使用 Jackson JsonNode
【发布时间】:2022-01-06 04:11:22
【问题描述】:

我正在使用 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();
    }
}

}

【问题讨论】:

  • objectNode1.equals(objectNode1) 中有错字吗? objectNode1 与自身进行比较并更新为 objectNode0.equals(objectNode1) 产生 false
  • 是的,错字。我会编辑那部分,谢谢

标签: java jackson assertj jsonnode


【解决方案1】:

JsonUnit 通常是 JSON 相关断言的更好候选者,也是 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    相关资源
    最近更新 更多