我正在使用Hamcrest Matcher来比较两个
JSON对象.比较方法使用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中也显示了不同的排序,作为错误的一部分.
最佳答案 我到目前为止能做的最好:
@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],...>