karate - 在匹配响应中找到的数组中对象的索引 [*]
问题描述
是否可以获得a的索引值
* match response.Services[*] contains { "Service": "xyz"}
我希望稍后重用它以对同一 Service 对象进行更具体的测试。这里引用了一个__loop
变量,但我想我不太明白如何应用它。
解决方案
我喜欢你的问题,你肯定将空手道推向了极限,我也不得不努力思考来回答这些问题:)
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]
如果你真的无法升级,你可以编写一个函数来手动循环数组,上面的例子应该会给你一个解决方案。
推荐阅读
- c# - 强制枚举以返回通用 C# 7.3
- python-3.x - 我可以创建一个函数来在每个时间间隔两个返回之间切换吗?
- ios - 如何使用一个tableview的按钮自动选择另一个tableview的按钮全部
- flutter - 如何根据 dart 中另一个 Stream 的数据创建一个新的 Stream?
- wordpress - 有没有办法根据第一个贝宝账户的销售额向第二个贝宝账户汇款?
- android - Android MediaPlayer:将外部视频文件中的帧渲染到背景相机帧上的纹理
- sql - timescaledb-tune 问题
- c# - Catel 和 TCP 连接
- html - 如何将 favicon 添加到 Hugo 网站
- android - 在项目“:app”中找不到任务“installDebug”(npx react-native run-android 问题)