【问题标题】:How to check a value matches with another correpsonding value in a json response如何检查一个值是否与json响应中的另一个对应值匹配
【发布时间】:2017-02-26 16:05:27
【问题描述】:

检查 json 响应值的每个实例是否与脚本断言中的另一个 json 响应值匹配的最动态方法是什么?

我的意思是说我有以下回复:

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

                "xxx": xxx

            }],

            "totalPrice": xxx
        },

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

}

我想检查第一个房价是否与第一个 totalPrice 匹配,第二个 roomPrice 是否与第二个 totalPrice 匹配。它必须是动态的,因为我可能会得到许多不同的实例,所以我不能简单地查看带有 [0] 和 [1] 的 json。虚拟检查每个roomPrice 与其对应的totalPrice 匹配。

谢谢

【问题讨论】:

  • 你有一些有效的 JSON 吗?您问题中的 JSON 无效...
  • 我会给你一些有效的 json
  • 您是否使用已验证副本的主副本/黄金副本,并且当前响应将与之进行比较?
  • 给你,包含有效的 json
  • 或者只是roomPrice要与来自同一响应的totalPrice匹配?

标签: json rest groovy soapui


【解决方案1】:

所以给定Json作为变量:

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

                "roomPrice": 618.4

            }],

            "totalPrice": 618.4
        },

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

}'''

然后我们可以使用以下脚本:

import groovy.json.*

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

如您所见,我使用sum 将所有 roomInformation.roomPrice 值相加。在您的示例中,您只有一个价格,所以这很好。它还涵盖了您有多个房间加起来构成总数的情况

【讨论】:

  • 'hotel' 是否像每个 'hotels' 的变量名?
  • 另外,如果我想通过 log.info 测试查看值,为了确保它是正确的,写入 log.info 的正确方法是什么?
  • @BruceyBandit 是的,hotelhotelseach 元素的变量名称。如果您想注销,只需执行log.info "individual: ${hotel.roomInformation.roomPrice} == total:${hotel.totalPrice}" 或类似操作
【解决方案2】:

这里是script assertion,用于检查每个roomPrice是否与totalPrice匹配。

编辑:基于 OP 提供的完整回复 here

脚本断言

//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' }

【讨论】:

  • 我正在尝试 Rao 和 Tim 的回答
  • 根据您的其他回复,可能需要更改脚本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多