Mur*_*ham 5 java json jsonassert
我在一个使用 REST 接口的开源项目中工作。为了验证(将实际响应与预期匹配)我们在 JUnit 中的其余接口,我们想使用 JSONAssert。(https://github.com/skyscreamer/JSONassert)。但是我的用法有问题。请帮助解决它。
Expected JSON:
{
"objectId": "[^\\s]",
"protocol": "[^\\s]",
"hostName": "[^\\s]",
"port": "[^\\s]",
"commParams": "[^\\s]"
}
Run Code Online (Sandbox Code Playgroud)
备注:objectId/protocol/hostName/port/commParams 可以是任何值但不能为空
Actual JSON:
{
"objectId": "controller2",
"protocol": "ftp",
"hostName": "sdnorchestrator",
"port": "21",
"commParams": "username:tomcat, password:tomdog"
}
Run Code Online (Sandbox Code Playgroud)
问题1:JSON Assert的哪个接口,我需要使用哪个接口来解决上面的问题:下面一个?
JSONAssert.assertEquals("Expected JSON", "Actual JSON" new CustomComparator(
JSONCompareMode.LENIENT_ORDER, new Customization(PREFIX, new RegularExpressionValueMatcher<Object>())));
Run Code Online (Sandbox Code Playgroud)
问题 2:这里的 PREFIX 应该是什么?(我尝试使用“ ”、“.”、“ . ”但没有成功)
也欢迎针对上述问题提出任何其他建议(JSONAssert 除外)。
如果要全局应用正则表达式自定义JSONAssert,您可以构造一个Customizationwith path = "***",并使用不带参数的构造RegularExpressionValueMatcher函数。
例子:
final String expectedJson = "{objectId: \"[^\\s]+\", protocol: \"[^\\s]+\"}";
final String actualJson = "{\"objectId\": \"controller2\", \"protocol\": \"ftp\"}";
JSONAssert.assertEquals(
expectedJson,
actualJson,
new CustomComparator(
JSONCompareMode.LENIENT,
new Customization("***", new RegularExpressionValueMatcher<>())
)
);
Run Code Online (Sandbox Code Playgroud)
此断言成功通过(使用 JSONassert 版本 1.5.0 进行测试)。
我找到了更好的替代方案。使用 JsonSchema 验证器可以解决大部分问题(http://json-schema.org/)。在预期响应中写入 json 架构,并使用 json 验证器 jar 对其进行验证。(json-schema/json-schema-validator-2.0.1.jar.zip(166 k))