Java 断言一个类似于映射列表的JSON包含另一个JSON
我有一个测试,试图断言RESTAPI调用中的acutal json对象是否包含我硬编码的预期json。 我的实际JSON看起来像Java 断言一个类似于映射列表的JSON包含另一个JSON,java,json,Java,Json,我有一个测试,试图断言RESTAPI调用中的acutal json对象是否包含我硬编码的预期json。 我的实际JSON看起来像 { "data": [{ "requiredness": "required", "multi_value": false, "editable": true, "name": "name__v", "type": "String", "max_length": 5
{
"data": [{
"requiredness": "required",
"multi_value": false,
"editable": true,
"name": "name__v",
"type": "String",
"max_length": 50
}, {
"requiredness": "required",
"multi_value": false,
"editable": true,
"name": "label__v",
"type": "String",
"max_length": 100
}, {
"requiredness": "required",
"multi_value": false,
"editable": true,
"name": "active__v",
"type": "Boolean"
}, {
"requiredness": "required",
"component": "Doctype",
"multi_value": false,
"editable": true,
"name": "type__v",
"type": "Component"
}, {
"requiredness": "conditional",
"component": "Doctype",
"multi_value": false,
"editable": true,
"name": "subtype__v",
"type": "Component"
}, {
"requiredness": "optional",
"component": "Doctype",
"multi_value": false,
"editable": true,
"name": "classification__v",
"type": "Component"
}, {
"requiredness": "optional",
"multi_value": false,
"editable": true,
"name": "filing_model__v",
"type": "Object"
}],
"responseStatus": "SUCCESS"
}
我想声明,以下预期的JSON只包含一个映射,来自映射列表:
{
"data":[
{
"requiredness":"required",
"multi_value":false,
"editable":true,
"name":"name__v",
"type":"String",
"max_length":50
}
],
"responseStatus":"SUCCESS"
}
这是我的测试
public void test(){
JSONObject actualjson = callAPI(endpoint);
JSONObject expectedjson =new JSONObject(expectedOutput);
Assert.assertThat(actualjson.toString(),CoreMatchers.containsString(ExpectedjsonObj.toString()));
}
由于空格,我得到一个例外:
Expected: a string containing "{\"data\":[{\"requiredness\":\"required\",\"multi_value\":false,\"editable\":true,\"name\":\"name__v\",\"type\":\"String\",\"max_length\":50}],\"responseStatus\":\"SUCCESS\"}"
但所得到的是
"{"data":[{"requiredness":"required","multi_value":false,"editable":true,"name":"name__v","type":"String","max_length":50},{"requiredness":"required","multi_value":false,
既然您正在测试REST API调用的输出,并且输出中的顺序不一定得到保证,那么断言我的实际JSON中的映射列表包含我期望的映射(也可以是一个列表)的最佳方法是什么,解决方案正是您所表达的您不想做的事情:断言JSONObject中每个元素的存在性。幸运的是,您可以利用该库来完成这项工作。您正在测试的方法实际上是什么?该方法的目的是编写JSON吗?或者该方法的目的是操纵正在编写的JSON所表示的对象?或者这种方法两者兼有?添加测试方法和测试用例会很有帮助。请尝试使用json assert进行检查,因为json键的顺序可能无法保证。你不能仅仅用字符串来比较它们,因为你是用JSONObject来说话的,我有以下问题:你是在实现JSON编写器吗?或者“编写JSON”是大型应用程序的一个小功能,在这个应用程序中JSONObject实际上被用作另一段数据的表示?被测试的代码实际上在做什么?有没有一个特别的原因让您不把JSON编写的细节留给经过验证的框架,例如?无论如何,我建议不要使用字符串比较,而是比较数据模型中的元素。由于我的API响应包含一长串元数据,我不想断言测试中每个元素的存在。例如,如果我想确保在我的实际json中存在带有“name”:“name__v”的元素和带有“name”:“subtype__v”的元素,我如何向测试中添加这样的断言。