Karate框架使用contains deep对比时忽略嵌套字段的方法
在Karate中使用
contains deep对比JSON时忽略指定字段 在Karate中实现忽略指定字段的JSON对比,有两种简洁可靠的方案,完全适配你的需求场景:
方案1:移除忽略字段后对比
直接从两个待对比的JSON对象中删除不需要校验的字段,再执行contains deep匹配,是最直观的实现方式。
场景1:仅显示city字段差异
* def response1 = { id: 1, name: 'John', address: { city: 'New York', state: 'NY' } } * def response2 = { id: 1, name: 'John', address: { city: 'California', state: 'CA' } } // 批量移除两个响应中的state字段(支持点路径语法定位嵌套字段) * karate.remove(response1, 'address.state') * karate.remove(response2, 'address.state') // 执行对比,此时仅校验剩余字段,报告只会显示city的差异 * match response1 contains deep response2
场景2:忽略state后无差异
* def response1 = { id: 1, name: 'John', address: { city: 'New York', state: 'NY' } } * def response2 = { id: 1, name: 'John', address: { city: 'New York', state: 'CA' } } // 移除state字段 * karate.remove(response1, 'address.state') * karate.remove(response2, 'address.state') // 剩余字段完全匹配,报告显示无差异 * match response1 contains deep response2
方案2:使用通配符跳过字段校验
如果不想修改原始响应对象,可以在匹配规则中用__(双下划线通配符)标记需要忽略的字段,Karate会自动跳过该字段的校验。
场景1:仅显示city字段差异
* def response1 = { id: 1, name: 'John', address: { city: 'New York', state: 'NY' } } * def response2 = { id: 1, name: 'John', address: { city: 'California', state: 'CA' } } // 直接在匹配规则中忽略address.state,同时校验其他字段 * match response1 contains deep { id: 1, name: 'John', address: { city: '#present', state: '__' } } // 或者动态修改response2的state为通配符后对比 * match response1 contains deep karate.set(response2, 'address.state', '__')
场景2:忽略state后无差异
* def response1 = { id: 1, name: 'John', address: { city: 'New York', state: 'NY' } } * def response2 = { id: 1, name: 'John', address: { city: 'New York', state: 'CA' } } // 忽略state字段后执行对比,报告显示无差异 * match response1 contains deep karate.set(response2, 'address.state', '__')
额外提示
- 若需忽略多个字段,可使用批量移除语法:
karate.remove(response, ['field1', 'nested.field2']) - 点路径语法支持任意层级的嵌套字段定位,比如
user.contact.address.zip - 通配符
__表示完全跳过字段校验,无论字段值是什么都视为匹配
内容的提问来源于stack exchange,提问作者rajeev ranjan
相关产品推荐
相关产品推荐

