您可以为此使用自定义。例如,如果您需要忽略名为“ timestamp”的顶级属性,请使用:
JSONAssert.assertEquals(expectedResponseBody, responseBody, new CustomComparator(JSONCompareMode.LENIENT, new Customization("timestamp", (o1, o2) -> true)));也可以使用路径表达式,例如“
entry.id”。在自定义中,您可以使用任何喜欢的方法比较两个值。上面的示例始终返回true,无论期望值和实际值是多少。如果需要,您可以在那里做更复杂的事情。
完全可以忽略多个属性的值,例如:
@Testpublic void ignoringMultipleAttributesWorks() throws JSonException { String expected = "{"timestamp":1234567, "a":5, "b":3 }"; String actual = "{"timestamp":987654, "a":1, "b":3 }"; JSONAssert.assertEquals(expected, actual, new CustomComparator(JSONCompareMode.LENIENT, new Customization("timestamp", (o1, o2) -> true), new Customization("a", (o1, o2) -> true) ));}使用自定义项时有一个警告:要以自定义方式比较其值的属性必须存在于实际JSON中。如果即使属性根本不存在,也希望比较成功,则必须重写CustomComparator,例如:
@Testpublic void extendingCustomComparatorToAllowToCompletelyIgnoreCertainAttributes() throws JSonException { // AttributeIgnoringComparator completely ignores some of the expected attributes class AttributeIgnoringComparator extends CustomComparator{ private final Set<String> attributesToIgnore; private AttributeIgnoringComparator(JSonCompareMode mode, Set<String> attributesToIgnore, Customization... customizations) { super(mode, customizations); this.attributesToIgnore = attributesToIgnore; } protected void checkJsonObjectKeysExpectedInActual(String prefix, JSonObject expected, JSonObject actual, JSonCompareResult result) throws JSonException { Set<String> expectedKeys = getKeys(expected); expectedKeys.removeAll(attributesToIgnore); for (String key : expectedKeys) { Object expectedValue = expected.get(key); if (actual.has(key)) { Object actualValue = actual.get(key); comparevalues(qualify(prefix, key), expectedValue, actualValue, result); } else { result.missing(prefix, key); } } } } String expected = "{"timestamp":1234567, "a":5}"; String actual = "{"a":5}"; JSONAssert.assertEquals(expected, actual, new AttributeIgnoringComparator(JSONCompareMode.LENIENT, new HashSet<>(Arrays.asList("timestamp"))) );}(使用这种方法,您仍然可以使用“自定义”以所需的方式比较其他属性的值。)



