Big Hendo Big Hendo - 8 months ago 66
Groovy Question

How to iterate through a DTOs in a JSON to perform assertions?

I am a beginner in programming and at the moment I am performing so SOAP UI tests that rely on groovy scripting. Below I want to assert that everything within the policies DTO contains the correct values:

Now I know how to perform an assert by simply include

json.policies.id[0]
and
json.policies.id[1]
etc but this seems a little bit long winded. I am assuming there is a better way by iterating through the DTOs within policies to ensure the ids are correct and the provider id is correct. My question is that can somebody provide me an example for me to work with to know how to code this please?

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

assert json.policies.id[0].toString() = '28'
assert json.policies.id[1].toString() = '31'
assert json.policies.id[2].toString() = '34'
assert json.policies.id[3].toString() = '37'

assert json.policies.providerId[0].toString() = '41'
assert json.policies.providerId[1].toString() = '41'
assert json.policies.providerId[2].toString() = '41'
assert json.policies.providerId[3].toString() = '41'


Thank you

Answer Source

You can simplify your assertion to a single line, like:

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

def policies = [[id: 28, providerId: 41], [id: 31, providerId: 41], [id: 34, providerId: 41], [id: 37, providerId: 41]]

assert json.policies == policies
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download