How to check a value matches with another correpso

2019-07-29 11:49发布

问题:

What is the most dynamic way of checking each instance of a json response value matches another json response value within a script assertion?

What I mean is lets say I have the following response below:

   {
    "xxx": [{
            "roomInformation": [{

                "xxx": xxx

            }],

            "totalPrice": xxx
        },

        {
            "roomInformation": [{
                xxx: xxx
            }],
            "totalPrice": xxx
        }
    ]

}

I want to check that the first room price to match with the first totalPrice and the second roomPrice to match with the second totalPrice. It has to be dynamic as I may get many different instances of this so I can't simply just look through the json with [0] and [1]. Virtually check each roomPrice matches with its corresponding totalPrice.

Thanks

回答1:

Here is the script assertion to check each roomPrice is matching or not with totalPrice.

EDIT: based on OP's full response provided here

Script Assertion:

//Check if the response is not empty
assert context.response, "Response is empty or null"

def json = new groovy.json.JsonSlurper().parseText(context.response)
def sb = new StringBuffer()
json.regions.each { region ->
    region.hotels.each { hotel ->
        (hotel?.totalPrice == hotel?.roomInformation[0]?.roomPrice) ?: sb.append("Room price ${hotel?.roomInformation[0]?.roomPrice} is not matching with total price ${hotel.totalPrice}")    
    }
}
if (sb.toString()) {
    throw new Error(sb.toString())
} else { log.info 'Prices match' }


回答2:

So given the Json as a variable:

def jsonTxt = '''{
    "hotels": [{
            "roomInformation": [{

                "roomPrice": 618.4

            }],

            "totalPrice": 618.4
        },

        {
            "roomInformation": [{
                "roomPrice": 679.79
            }],
            "totalPrice": 679.79
        }
    ]

}'''

We can then use the following script:

import groovy.json.*

new JsonSlurper().parseText(jsonTxt).hotels.each { hotel ->
   assert hotel.roomInformation.roomPrice.sum() == hotel.totalPrice
}

As you can see, I'm using sum to add all the roomInformation.roomPrice values together. In your example, you only have one price, so this will be fine.. And it will also cover the case where you have multiple rooms adding up to make the total