There are two JSON strings to be compared by JSONAssert:
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"
]
}
The two JSON strings are expected to be equal:
- Compare
items
inSTRICT
mode, i.e. "Strict checking. Not extensible, and strict array ordering." - Compare
auths
inNON_EXTENSIBLE
mode, i.e. "Non-extensible checking. Not extensible, and non-strict array ordering."
In other words, the comparison is order-sensitive for items
but order-tolerant for auths
.
The JSONAssert
code is:
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();
}
The TestUtil
code for comparing two String lists ignoring order is:
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);
}
}
It gets error because it doesn't comply with JSONAssert
convention, but I didn't find another solution yet. Someone help me out?