我正在使用JSON单元来比较两个json响应。 但是,UUID 每次都是动态的,因此响应总是不同的,下面的内容不会忽略"id",并且始终将其标记为不同。
private void assertWithIgnore(String endpoint, String expected, int code) throws IOException {
try {
response.then()
.statusCode(code)
.contentType(ContentType.JSON);
if (compare) {
assertJsonEquals(response.asString(),
resource("expected/" + expected),
JsonAssert.whenIgnoringPaths("item[*].id"));
} else {
Assert.fail("Not comparing response, write direct to file!");
}
} catch (AssertionError error) {
FileUtils.writeStringToFile(getResultFile(expected), response.prettyPrint());
failures.put(baseURL + basePath + endpoint, response);
throw error;
}
}
下面是 JSON 的一个小示例:
{
"item": [
{
"id": "1",
"title": "Hello"
}
]
}
用以下内容解决了上述问题:
JsonAssert.setOptions(IGNORING_VALUES);
使用 JsonAssert,这也应该有效...准备?
ArrayValueMatcher<Object> arrayValueMatcher = new ArrayValueMatcher<>(new CustomComparator(JSONCompareMode.LENIENT, new Customization("item[*].id", new ValueMatcher<Object>() {
@Override
public boolean equal(Object o1, Object o2) {
return true;
}
})));
Customization arrayValueMatcherCustomization = new Customization("item", arrayValueMatcher);
CustomComparator customArrayValueComparator = new CustomComparator(JSONCompareMode.LENIENT, arrayValueMatcherCustomization);
JSONAssert.assertEquals(expect, actual, customArrayValueComparator);
我正在使用库版本 1.5.0