JSONAssert将比较两个JSON字符串:
StringA
{
"items": [
"SfWn8eQ",
"QiOiJrw",
"2Npc2Nv"
],
"auths": [
"5895c0a1-0fa9-4222-bbfb-5f96f6737cd7",
"415499a6-daa3-45b7-b967-83aa94a38da1",
"5d572399-a2ae-4bc4-b989-e2115028612e"
]
}StringB
{
"items": [
"SfWn8eQ",
"QiOiJrw",
"2Npc2Nv"
],
"auths": [
"415499a6-daa3-45b7-b967-83aa94a38da1",
"5d572399-a2ae-4bc4-b989-e2115028612e",
"5895c0a1-0fa9-4222-bbfb-5f96f6737cd7"
]
}预期两个JSON字符串是相等的:
STRICT模式下的items。“严格检查,不可扩展,严格数组ordering."auths在NON_EXTENSIBLE模式下,即“不可扩展的检查。不可扩展的,以及非严格的数组排序。”换句话说,这种比较对items是顺序敏感的,而对于auths则是可接受的.
JSONAssert代码是:
CustomComparator comparator = new CustomComparator(JSONCompareMode.NON_EXTENSIBLE,
new Customization("auths",
// A lenient comparison for auths. Compare ignoring the order.
(o1, o2) -> (
TestUtil.equals(((List<String>)o1), ((List<String>)o2))
)
)
);
try {
JSONAssert.assertEquals(expected, actual, comparator);
} catch (JSONException e) {
Assert.fail();
}用于比较忽略顺序的两个字符串列表的TestUtil代码是:
public class KmsAgentTestUtil {
public static boolean equals(List<String> auths1, List<String> auths2) {
if (CollectionUtils.isEmpty(auths1) && CollectionUtils.isEmpty(auths2)) {
return true;
}
Collections.sort(auths1);
Collections.sort(auths2);
return auths1.equals(auths2);
}
}它会出错,因为它不符合JSONAssert约定,但我还没有找到其他解决方案。有人帮我吗?
发布于 2021-06-22 19:20:33
这可以通过ModelAssert - https://github.com/webcompere/model-assert来解决,它允许在每个路径的基础上放松比较顺序。OP问题的示例:
assertJson(stringA)
.where()
.at("/auths").arrayInAnyOrder()
.isEqualTo(stringB);https://stackoverflow.com/questions/63325535
复制相似问题