【问题标题】:Matching partial objects to table data [duplicate]将部分对象与表数据匹配[重复]
【发布时间】:2020-11-20 12:32:33
【问题描述】:

我目前正在评估空手道,以替代我们自己开发的 API 测试。我有一个服务返回这样的数据:

{
  "items": [
    {
      "id": "1",
      "enabled": true,
      "foo": 1,
    },
    ...
  ],
  ...
}

每个项目所属的属性做不同的功能,我想分别测试一下。

例如,为了测试项目启用,我想检查enabled 属性对于给定id 的值是否正确。

我试过这样设置;

Feature: Partial object matching
  Background:
    Given table items
    |id  |enabled|
    | '1'|true   |
    | '2'|true   |
    | '3'|false  |

  Scenario: match with all properties specified -- this passes
    * def response = { items: [ { id: '3', enabled: false }, { id: '1', enabled: true }, { id: '2', enabled: true } ] }
    * match $response.items contains only items


  Scenario: match with partial properties -- how can I make this pass (while also testing for something sensible)?
    * def response = { items: [ { id: '3', enabled: false, foo: 1 }, { id: '1', enabled: true, foo: 1 }, { id: '2', enabled: true, foo: 1 } ] }
    * match $response.items contains only items

真正的item 对象相当粗壮,包含更多属性和嵌套对象,我宁愿不指定完整的预期结构,因为它们涉及许多不同的功能,并且某些属性本质上是动态的。

有没有优雅的match 来做到这一点,还是我必须求助于脚本?

【问题讨论】:

    标签: karate


    【解决方案1】:

    这似乎做对了;

    Feature: Partial object matching
      Background:
        Given def filterTableKeys = read('filterTableKeys.js')
        Given table items
        |id  |enabled|
        | '1'|true   |
        | '2'|true   |
        | '3'|false  |
    
      Scenario: match with all attributes
        * def response = { items: [ { id: '3', enabled: false }, { id: '1', enabled: true }, { id: '2', enabled: true } ] }
        * match $response.items contains only items
    
      Scenario: match with partial attributes
        * def response = { items: [ { id: '3', enabled: false, foo: 1 }, { id: '1', enabled: true, foo: 1 }, { id: '2', enabled: true, foo: 1 } ] }
        * def responseItems = $response.items
        * def responseItems2 = filterTableKeys(responseItems, items)
        * match responseItems2 contains only items
    

    filterTableKeys.js 定义为

    function fn(items, table) {
        var mapper = function(v) { return karate.filterKeys(v, table[0]) }
        return karate.map(items, mapper)
    }
    

    虽然感觉不是很优雅,所以任何关于如何做到更具声明性/更少命令性/“脚本”的提示将不胜感激。


    编辑

    正如下面提到的Babu Sekaran,这似乎工作得很好

      Scenario: match with partial attributes
        * def response = { items: [ { id: '3', enabled: false, foo: 1 }, { id: '1', enabled: true, foo: 1 }, { id: '2', enabled: true, foo: 1 } ] }
        * match $response.items contains deep items
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    相关资源
    最近更新 更多