如何使用Karate框架验证两个JSON不同键的对应值一致性
Karate框架验证JSON映射键值一致性的实现方法
用Karate框架验证两个JSON中不同映射键的值是否一致,有两种实用方式:
一、逐一验证单个字段
如果映射字段不多,直接写match语句逐个对比最直观:
# 定义两个JSON对象 * def json1 = { "details": { "employee": "tester", "id": "1234", "salary": "20000" } } * def json2 = { "information": { "name": "tester", "reference": "1234", "amount": "20000" } } # 按映射关系逐一验证值是否相等 * match json1.details.employee == json2.information.name * match json1.details.id == json2.information.reference * match json1.details.salary == json2.information.amount
二、批量验证(适合多字段场景)
如果需要验证的映射字段较多,先定义映射关系表,再通过循环批量验证,避免重复代码:
# 定义两个JSON对象 * def json1 = { "details": { "employee": "tester", "id": "1234", "salary": "20000" } } * def json2 = { "information": { "name": "tester", "reference": "1234", "amount": "20000" } } # 定义键映射表:键是JSON1的字段路径,值是JSON2对应的字段路径 * def fieldMappings = { "details.employee": "information.name", "details.id": "information.reference", "details.salary": "information.amount" } # 遍历映射表完成批量验证 * karate.forEach(fieldMappings, (path1, path2) => { match karate.get(json1, path1) == karate.get(json2, path2) })
额外说明
如果遇到值类型不一致的情况(比如JSON1中是字符串"20000",JSON2中是数字20000),可以用==~进行宽松匹配,替换上述代码中的==即可。
内容的提问来源于stack exchange,提问作者KK12
相关产品推荐
相关产品推荐

