比较json对象时包含抛出异常

时间:2018-07-11 11:32:22

标签: karate

我正在尝试使用contains来比较json,比较时却出错。

Feature:

Scenario:
Given def cat = 
"""
{
  name: 'Billie',
  kittens: [
    { id: 23, name: 'Bob' },
    { id: 42, name: 'Wild' },
    { id: 43, name: 'Wild', val: 'test', charging_model : {model: "test",overage : "NAN"}}
  ]
}
"""
Then match cat.kittens contains [{ id: 42, name: 'Wild' }, { id: 23, name: 'Bob' }]
Then match $cat.kittens contains { id: 43, name: '#string', charging_model : {overage : "NAN"} }

例外:

com.intuit.karate.exception.KarateException: path: $.kittens[*], actual: [{"id":23,"name":"Bob"},{"id":42,"name":"Wild"},{"id":43,"name":"Wild","val":"test","charging_model":{"model":"test","overage":"NAN"}}], expected: {id=43, name=#string, charging_model={overage=NAN}}, reason: actual value does not contain expected
    at com.intuit.karate.StepDefs.matchNamed(StepDefs.java:540)
    at com.intuit.karate.StepDefs.matchContains(StepDefs.java:532)
    at ✽.Then match $cat.kittens contains { id: 43, name: '#string', charging_model : {overage : "NAN"} }

如果我的json不包含其工作的json对象,

 {
          name: 'Billie',
          kittens: [
            { id: 23, name: 'Bob' },
            { id: 42, name: 'Wild' },
            { id: 43, name: 'Wild', val: 'test'}
          ]
        }
Then match $cat.kittens contains { id: 43, name: '#string' } //It is working

请帮助我如何使用包含在json中的json对象的contains比较json。

先谢谢了。

1 个答案:

答案 0 :(得分:1)

考虑一下。您实际上正在执行3个级别的contains,第一个是数组,接下来的两个是JSON部分对象:)

如果您执行完全匹配(完整的JSON对象),它将按预期工作:

Then match cat.kittens contains { id: 43, name: '#string', val: 'test', charging_model: { model: 'test', overage : 'NAN' } }

如果您不想指定所有字段,则需要将JSON分解为如下所示的命名段:

* def testModel = { overage: 'NAN' } 
* def testKitten = { charging_model: '#(^testModel)' }
* match cat.kittens contains '#(^testKitten)'

在文档https://github.com/intuit/karate#contains-short-cuts

中对此进行了详细说明。