rpa*_*ali 5 java junit json hamcrest matcher
我正在使用 Hamcrest Matcher 来比较两个 JSON 对象。compare 方法使用 Gson 解析器。
匹配器效果很好,但是当两个 JSON 不相同时,我只能显示如下消息:
Expected: <[{"data":"data1","application":{"id":"1"}}]>
but: <[{"data":"data1","application":{"id":"2"}}]>
Run Code Online (Sandbox Code Playgroud)
这不是很有帮助,我想显示哪些元素不匹配,例如junit的assertEquals:
expected:<...a1","application":{"[filtered":false,"id":"1"]...> but was:<...a1","application":{"[id":"2"...>
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这一目标?
编辑:
@Override
protected void describeMismatchSafely(JsonElement item,
Description mismatchDescription) {
//mismatchDescription.appendValue(item);
assertEquals(item.toString(), originalJson.toString());
}
Run Code Online (Sandbox Code Playgroud)
但这会给我:
expected:<...a1","application":{"[filtered":false,"id":"2"]...>
but was:<...a1","application":{"[id":"1","filtered":false],...>
Run Code Online (Sandbox Code Playgroud)
请注意,唯一的区别在于“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);
}
}
Run Code Online (Sandbox Code Playgroud)
这给了我
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],...>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1232 次 |
| 最近记录: |