How to validate nested response using REST Assured

2019-07-20 15:39发布

问题:

Need help to validate particular JSON parameter from below response using REST Assured library.

I tried some of the options to validate other similar parameter as shown below but it didn't work.

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

If I want to validate "resultCode" & "subscriberIdType" from below response then how can I do it?

[  
{  
    "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"
                        }
                    ]
                }
            ]
        }
    ]
}

]

回答1:

This is one way:

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

You can read up on Groovy collections and GPath to learn more.