gpt4 book ai didi

java - 具有 junit 风格差异的 Hamcrest 匹配器

转载 作者:搜寻专家 更新时间:2023-11-01 03:25:47 25 4
gpt4 key购买 nike

我正在使用 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],...>

关于java - 具有 junit 风格差异的 Hamcrest 匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14163410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com