5

我正在一个使用 REST 接口的开源项目中工作。为了验证(将实际响应与预期匹配)我们在 JUnit 中的其余接口,我们想使用 JSONAssert。(https://github.com/skyscreamer/JSONassert)。但是我的用法有问题。请帮助解决它。

Expected JSON:
{
"objectId": "[^\\s]",
"protocol": "[^\\s]",
"hostName": "[^\\s]",
"port": "[^\\s]",
"commParams": "[^\\s]"
}

备注:objectId/protocol/hostName/port/commParams 可以是任何东西但不能为空

Actual JSON:
{
"objectId": "controller2",
"protocol": "ftp",
"hostName": "sdnorchestrator",
"port": "21",
"commParams": "username:tomcat, password:tomdog"
}

问题1:JSON Assert的哪个接口,我需要用哪个接口来解决上面的问题:下一个?

JSONAssert.assertEquals("Expected JSON", "Actual JSON" new CustomComparator(
    JSONCompareMode.LENIENT_ORDER, new Customization(PREFIX, new        RegularExpressionValueMatcher<Object>())));

问题2:这里的PREFIX应该是什么?(我试过用“ ”、“.”、“ . ”但没有成功)

也欢迎针对上述问题的任何其他建议(JSONAssert 除外)。

4

3 回答 3

4

如果要全局应用正则表达式自定义with 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<>())
    )
);

此断言成功通过(使用 JSONassert 版本 1.5.0 测试)。

于 2018-09-19T14:01:02.827 回答
1

我找到了更好的选择。使用 JsonSchema 验证器可以解决大部分问题(http://json-schema.org/)。将 json 模式写入预期响应并使用 json 验证器 jar 对其进行验证。(json-schema/json-schema-validator-2.0.1.jar.zip(166 k))

于 2016-09-29T10:49:32.140 回答
0

我也无法获得除 RE 之外的路径。最终我只是过度使用 DefaultComparator 的 compareValues 来强制它将 RegularExpressionValueMatcher 应用于所有路径:

import org.json.JSONException;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareResult;
import org.skyscreamer.jsonassert.RegularExpressionValueMatcher;
import org.skyscreamer.jsonassert.ValueMatcherException;
import org.skyscreamer.jsonassert.comparator.DefaultComparator;
import static org.skyscreamer.jsonassert.JSONCompareMode.STRICT;
    ...

final RegularExpressionValueMatcher reMatcher = new RegularExpressionValueMatcher();

JSONAssert.assertEquals( "{\"key\":\"v.*\"}", "{\"key\":\"value\"}",
    new DefaultComparator( STRICT ) {

        @Override
        public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
            try {
                if( !reMatcher.equal(actualValue, expectedValue) ) result.fail(prefix, expectedValue, actualValue);
            } catch( ValueMatcherException e ) { result.fail(prefix, e); }
        }

    }
于 2017-06-02T23:58:47.103 回答