断言一个JSON(就像一个地图列表)包含另一个JSON

时间:2016-05-06 16:42:37

标签: java json

我有一个测试试图断言,如果来自其余API调用的acutal json对象包含我硬编码的预期JSON。 我的实际JSON看起来像

{
    "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,

断言我的实际JSON中的地图列表包含我期望的地图(也可能是列表)的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

由于您正在测试REST API调用的输出,并且输出中的订单不一定得到保证,因此解决方案正是您所表达的您不想做的事情:声明存在每个元素JSONObject的。幸运的是,JSONAssert库可以用来为你做这件事。