如何使用REST Assured验证嵌套响应?

时间:2015-04-12 03:23:17

标签: web-services api rest response rest-assured

需要帮助来使用REST Assured库从下面的响应中验证特定的JSON参数。

我尝试了一些选项来验证其他类似参数,如下所示,但它没有用。

.then().body("value.value.value.name", hasItems("balanceResultCode")).body("value.value.value.value", hasItems("0"));

如果我想验证" resultCode" &安培; " subscriberIdType"从下面的回复那我该怎么办?

[  
{  
    "name":"Id",
    "value":"11"
},
{  
    "name":"version",
    "value":null
},
{  
    "name":"header",
    "value":[  
        {  
            "name":"mVersion",
            "value":"1"
        },
        {  
            "name":"Name",
            "value":"BalQ"
        },
        {  
            "name":"appID",
            "value":"90091"
        },
        {  
            "name":"requestUid",
            "value":"REST_REQUQEST_1"
        },
        {  
            "name":"sessionId",
            "value":"REST_SESSION_1"
        },
        {  
            "name":"requestType",
            "value":"SomeRequestType"
        },
        {  
            "name":"requestNumber",
            "value":"REQ_111"
        },
        {  
            "name":"requestDuplicate",
            "value":"1"
        },
        {  
            "name":"serviceProvider",
            "value":1
        },
        {  
            "name":"username",
            "value":"user"
        },
        {  
            "name":"password",
            "value":"pass"
        },
        {  
            "name":"resultCode",
            "value":100
        }
    ]
},
{  
    "name":"content",
    "value":[  
        {  
            "name":"subscriberAddressing",
            "value":[  
                {  
                    "name":"subscriber",
                    "value":[  
                        {  
                            "name":"subscriberIdType",
                            "value":200
                        },
                        {  
                            "name":"subscriberIdValue",
                            "value":"1234567890"
                        }
                    ]
                }
            ]
        }
    ]
}

2 个答案:

答案 0 :(得分:3)

这是一种方式:

then().
       body("find { it.name == 'header' }.value.find { it.name == 'resultCode' }.value", is(100)).
       body("find { it.name == 'content' }.value.find { it.name == 'subscriberAddressing' }.value.find { it.name == 'subscriber' }.value.find { it.name == 'subscriberIdType'}.value", is(200));

您可以阅读Groovy集合和GPath以了解更多信息。

答案 1 :(得分:0)

首先您需要导入

import static org.hamcrest.CoreMatchers.equalTo;

之后,您可以按以下方式使用它

RestAssured.given().auth().oauth2(token).when().accept("application/json").get("someurl").then().statusCode(200).body("name[0]", equalTo("Anwar"));