How to check a value matches with another correpsonding value in a json response

妖精的绣舞 提交于 2019-12-11 07:54:57

问题


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



来源:https://stackoverflow.com/questions/42470806/how-to-check-a-value-matches-with-another-correpsonding-value-in-a-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!