5

我正在使用 Hamcrest Matcher 来比较两个 JSON 对象。compare 方法使用 Gson 解析器。

匹配器效果很好,但是当两个 JSON 不相同时,我只能显示如下消息:

Expected: <[{"data":"data1","application":{"id":"1"}}]>
     but: <[{"data":"data1","application":{"id":"2"}}]>

这不是很有帮助,我想显示哪些元素不匹配,例如junit的assertEquals:

expected:<...a1","application":{"[filtered":false,"id":"1"]...> but was:<...a1","application":{"[id":"2"...>

有没有办法做到这一点?

编辑:

@Override
protected void describeMismatchSafely(JsonElement item, 
                                      Description mismatchDescription) {
    //mismatchDescription.appendValue(item);
    assertEquals(item.toString(), originalJson.toString());
}

但这会给我:

expected:<...a1","application":{"[filtered":false,"id":"2"]...> 
but  was:<...a1","application":{"[id":"1","filtered":false],...>

请注意,唯一的区别在于“id:1”和“id:2”,但 junit 也向我显示 JSON 中的不同排序作为错误的一部分。

4

1 回答 1

2

到目前为止我能做的最好的:

@Override
protected void describeMismatchSafely(JsonElement expectedJson, 
                                      Description mismatchDescription) {

  mismatchDescription.appendValue(expectedJson).appendText("\ndifference:\n");

  try {
     assertEquals(expectedJson.toString(), originalJson.toString());
  }
  catch (ComparisonFailure e) {
     String message = e.getMessage();
     message = message.replace("expected:", "");
     message = message.replace("but was:", "");
     message = message.replaceFirst(">", ">\n");
     mismatchDescription.appendText(message);
  }
}

这给了我

Expected: <[{"data":"data1","application":{"id":"1"}}]>
     but: <[{"data":"data1","application":{"id":"2"}}]>
difference:
<...a1","application":{"[filtered":false,"id":"2"],...>
<...a1","application":{"[id":"1","filtered":false],...>
于 2013-01-05T05:56:32.380 回答