【问题标题】:JSONAssert ignore order for specific fieldJSONAssert 忽略特定字段的顺序
【发布时间】:2020-08-09 11:09:00
【问题描述】:

有两个 JSON 字符串要被 JSONAssert 比较:

字符串A

{
    "items": [
        "SfWn8eQ",
        "QiOiJrw",
        "2Npc2Nv"
    ],
    "auths": [
        "5895c0a1-0fa9-4222-bbfb-5f96f6737cd7",
        "415499a6-daa3-45b7-b967-83aa94a38da1",
        "5d572399-a2ae-4bc4-b989-e2115028612e"
    ]
}

字符串B

{
    "items": [
        "SfWn8eQ",
        "QiOiJrw",
        "2Npc2Nv"
    ],
    "auths": [
        "415499a6-daa3-45b7-b967-83aa94a38da1",
        "5d572399-a2ae-4bc4-b989-e2115028612e",
        "5895c0a1-0fa9-4222-bbfb-5f96f6737cd7"
    ]
}

两个 JSON 字符串应该相等:

  • STRICT 模式下比较items,即“严格检查。不可扩展,严格的数组排序。”
  • NON_EXTENSIBLE 模式下比较auths,即“不可扩展检查。不可扩展,非严格的数组排序。”

换句话说,比较对于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 约定而出错,但我还没有找到其他解决方案。有人帮帮我吗?

【问题讨论】:

  • “它得到错误”你得到什么错误?

标签: java jsonassert


【解决方案1】:

这可以通过 ModelAssert - https://github.com/webcompere/model-assert 解决,它允许在每个路径的基础上放宽比较顺序。 OP问题的例子:

assertJson(stringA)
    .where()
       .at("/auths").arrayInAnyOrder()
    .isEqualTo(stringB);

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 2010-12-03
    • 2012-02-01
    • 2011-02-24
    • 1970-01-01
    • 2020-03-07
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多