首页 > 解决方案 > 在匹配响应中找到的数组中对象的索引 [*]

问题描述

是否可以获得a的索引值 * match response.Services[*] contains { "Service": "xyz"}

我希望稍后重用它以对同一 Service 对象进行更具体的测试。这里引用了一个__loop变量,但我想我不太明白如何应用它。

标签: karate

解决方案


我喜欢你的问题,你肯定将空手道推向了极限,我也不得不努力思考来回答这些问题:)

match不允许您获得“找到的索引”甚至想到它的“循环位置”-实际上可能与 a 有关-match each但我离题了。

这将需要几行额外的代码,我真的认为你需要升级到 0.8.0。如果有帮助,我可以确认没有重大更改(除非您使用独立 JAR)。

新的karate.forEach()karate.match()函数允许您对数组执行非常复杂的操作。这里有 2 个例子:

Scenario: karate find index of first match (primitive)
    * def list = [1, 2, 3, 4]
    * def searchFor = 3
    * def foundAt = []
    * def fun = function(x, i){ if (x == searchFor) foundAt.add(i) }
    * eval karate.forEach(list, fun)
    * match foundAt == [2]

Scenario: karate find index of first match (complex)
    * def list = [{ a: 1, b: 'x'}, { a: 2, b: 'y'}, { a: 3, b: 'z'}]
    * def searchFor = { a: 2, b: '#string'}
    * def foundAt = []
    * def fun = function(x, i){ if (karate.match(x, searchFor).pass) foundAt.add(i) }
    * eval karate.forEach(list, fun)
    * match foundAt == [1]

如果你真的无法升级,你可以编写一个函数来手动循环数组,上面的例子应该会给你一个解决方案。


推荐阅读