Forum Discussion

harmans's avatar
harmans
Occasional Contributor
12 years ago

Assert JSON response using groovy

Hi ,

I would appreciate if you can please help.

I am testing Restful web services. Below is my JSON Request sent and Response received

Request : { "operation": "GetCountryCodes", "sessionid": 0};

Response : {
"PayLoad": "[{\"CountryKey\":3,\"Code\":12,\"Name\":\"Canada \",\"CurrencyKey\":40,\"CountryISOCode\":\"CAN\"},{\"CountryKey\":1,\"Code\":10,\"Name\":\"India \",\"CurrencyKey\":20,\"CountryISOCode\":\"IND\"},{\"CountryKey\":2,\"Code\":11,\"Name\":\"US \",\"CurrencyKey\":30,\"CountryISOCode\":\"USA\"}]",
"SessionId": "Den4eCm60rr2Wc6ukCl52lyV0UirUB/YSp0q3vWnk0DiwATaw7RzxTMaud38C1s6BxEnlZkebhSYZmxKEalGxgqtH6/4pBWfHMplQs5IlNVIET0jLN29quqm8WiddSp6oPUOLAJt9hG2k9VLI8YVR5RWDeoZuKqyK+OIEvJ03AeBXATEctFR/Hgxs0akux33",
"StatusId": 1
}

So i am trying to assert Payload data using groovy script assertion. Below are the steps:

1. Get response content as String, pass it to JsonSlurper to parse this string and create a hashmap

import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText response
def payload = slurper.parseText json.PayLoad

2. Read expected resonse stored in a text file (will call it ExpectedResponse.txt ) using groovy. The contents of ExpectedResponse.txt are
[{\"CountryKey\":3,\"Code\":12,\"Name\":\"Canada \",\"CurrencyKey\":40,\"CountryISOCode\":\"CAN\"},{\"CountryKey\":1,\"Code\":10,\"Name\":\"India \",\"CurrencyKey\":20,\"CountryISOCode\":\"IND\"},{\"CountryKey\":2,\"Code\":11,\"Name\":\"US \",\"CurrencyKey\":30,\"CountryISOCode\":\"USA\"}]

3. Validate the response received (stored in a hashmap ) from step 1 against expected response from step 2.

Please let me know
1. If this is the correct approach ?
2. Is there some other assertion which i should/could use for eg. xpath match or contains
3. Any help with the code for step 2 and step 3

Thanks in advance !
No RepliesBe the first to reply