Big Hendo
Big Hendo

Reputation: 185

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:

{
   "policies":    [
            {
         "xx": 28,
         "xxxxx": 41,
      },
            {
         "xx": 31,
         "xxxxxx": 41,
      },
            {
         "xx": 34,
         "xxxxx": 41,
      },
            {
         "xx": 37,
         "xxxxx": 41,
      }
   ]
   }

Now I know how to perform an assert by simply include json.policies.xx[0] and json.policies.xx[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 xxx are correct and the xxxxx 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.xx[0].toString() = '28'
assert json.policies.xx[1].toString() = '31'
assert json.policies.xx[2].toString() = '34'
assert json.policies.xx[3].toString() = '37'

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

Thank you

Upvotes: 1

Views: 148

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42272

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 = [[xx: 28, xxxxx: 41], [xx: 31, xxxxx: 41], [xx: 34, xxxxx: 41], [xx: 37, xxxxx: 41]]

assert json.policies == policies

Upvotes: 1

Related Questions