如何告诉assertJsonEquals忽略比较中的一个字段

时间:2018-05-04 09:25:26

标签: java json junit assert jsonunit

我正在使用JsonUnit assertJsonEquals

我在代码中执行以下操作:

assertJsonEquals(resource("ExpecedResponse.json"),
                         ActualResponse, when(IGNORING_ARRAY_ORDER));

ActualResponse有来自HTTP POST的响应。

ExpectedResponse.json是一个json文件,其中包含如下字段:

{
  "columnNames": [
    "date",
    "signalType",
    "userId",
  ],
  "values": [
    [
      222555888,
      "OUT",
      "000-000-111-444"
    ],
    [
      333666999,
      "IN",
      "000-000-222-333"
    ],
  ],
  "lastUpdatedTimestamp": "2018-01-26T00:00:00Z"
}

我将这两个回答与assertJsonEquals进行比较。

我的问题是:如何告诉它忽略检查lastUpdatedTimestamp字段,但使用assertJsonEquals或您推荐的任何其他库检查其他所有内容?!

如果我从ExpectedResponse.json中删除lastUpdatedTimestamp,那么它会抱怨它丢失了!

非常感谢您的帮助,谢谢。

3 个答案:

答案 0 :(得分:1)

您可以使用具有允许自定义的断言方法的库https://github.com/skyscreamer/JSONassert

这是一个传递测试的例子(这样忽略了time字段的值)

  @Test
  public void test() throws JSONException {
    JSONAssert.assertEquals("{x: 1, time:123}",
                            "{x: 1, time:234}",
                            new CustomComparator(
                              JSONCompareMode.STRICT,
                              Customization.customization("time", // json path you want to customize
                                                          new ValueMatcher() {
                                @Override public boolean equal(Object o1, Object o2) {
                                  return true; // in your case just ignore the values and return true
                                }
                              }))
    );
  }

这是我在示例中使用的assertEquals方法的javadoc的链接:http://jsonassert.skyscreamer.org/apidocs/org/skyscreamer/jsonassert/JSONAssert.html#assertEquals-java.lang.String-java.lang.String-org.skyscreamer.jsonassert.comparator.JSONComparator-

答案 1 :(得分:0)

正如documentation所说:

assertJsonEquals(
   "{\"root\":{\"test\":1, \"ignored\": 2}}", 
   "{\"root\":{\"test\":1, \"ignored\": 1}}", 
   whenIgnoringPaths("root.ignored")
);

答案 2 :(得分:0)

要仅忽略一个字段,请在预期的json中添加“ @IGNORE”,然后按如下所示设置setIgnorePlaceholder

JsonAssert.setTolerance(0.0000001);
JsonAssert.setOptions(IGNORING_ARRAY_ORDER);
JsonAssert.setIgnorePlaceholder("@IGNORE"); //You have to tag the ignored values in ExpecedResponse.json with "@IGNORE"

assertJsonEquals(resource("ExpecedResponse.json"),
                         ActualResponse);