空手道Intuit:如何验证动态json数组

时间:2018-05-30 11:37:44

标签: karate intuit

我一直在使用空手道,但我一直坚持如何验证这个动态数组。当我点击API时,数组苹果的大小不一。

如何逐个浏览数组并验证价格?

JSON:

  {
    "data": {
        "apple": [
            {
                "a": 0,
                "price": 1970,
                "date": "2018-05-30"
            },
            {
                "a": 1,
                "price": 1266,
                "date": "2018-05-31"
            },
            {
                "a": 2,
                "price": 1422,
                "date": "2018-06-01"
            }
        ]
    },
    "status_code": 200
}

2 个答案:

答案 0 :(得分:2)

我能够通过数据驱动的方法https://github.com/intuit/karate#data-driven-features

Feature: my test

Scenario: 
    * def response =
      """
      {
          "data": {
              "apple": [
                  {
                      "a": 0,
                      "price": 1970,
                      "date": "2018-05-30"
                  },
                  {
                      "a": 1,
                      "price": 1266,
                      "date": "2018-05-31"
                  },
                  {
                      "a": 2,
                      "price": 1422,
                      "date": "2018-06-01"
                  }
              ]
          },
          "status_code": 200
      }
      """
    * def va = call read('classpath:karate/examples/Assertions.feature') response.data.apple

在Assertions.feature文件中,我的代码是:

Scenario: 
    * match __arg contains { a: '#(__arg.a)', price: '#(__arg.price)', date: '#(dataBaseResult[__loop].date)' }

注意:

  1. 可以从任何来源提取预期数据。示例:数据库
  2. 记住'__loop'将给出数组的索引

答案 1 :(得分:0)

您是否了解match each语法?

* def response = 
"""
{
    "data": {
        "apple": [
            {
                "a": 0,
                "price": 1970,
                "date": "2018-05-30"
            },
            {
                "a": 1,
                "price": 1266,
                "date": "2018-05-31"
            },
            {
                "a": 2,
                "price": 1422,
                "date": "2018-06-01"
            }
        ]
    },
    "status_code": 200
}
"""
* match each response.data.apple == { a: '#? _ < 3', price: '#number', date: '#regex \\d{4}-\\d{2}-\\d{2}'}

编辑:如果你想做一些动态的东西,这就是空手道的JS互操作可以提供帮助

# work on the second item in the array
* def index = 1
* def second = response.data.apple[index]
* match second.price = 1266