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

How to validate nested response using 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"
                        }
                    ]
                }
            ]
        }
    ]
}

]

这是一种方式:

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 以了解更多信息。

首先你需要导入

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"));