You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Karate中逐索引比较两个不同列表的所有元素?

如何让Karate逐索引比较列表所有元素且不中途终止校验

默认使用match直接对比列表时,Karate会在第一个不匹配的元素处停止校验,无法获取后续元素的匹配情况。比如以下代码中,foo的第一个元素不符合预期时,剩余元素的对比会直接终止:

* def fun = function(i){ return i * 2 }
* def foo = karate.repeat(5, fun)
* match foo == [1, 1, 1, 6, 8]

要实现逐索引校验所有元素并输出全部差异,可以借助Karate的循环能力,逐个遍历列表索引进行元素对比:

方法一:使用karate.forEach遍历元素与索引

* def expected = [1, 1, 1, 6, 8]
* def fun = function(i){ return i * 2 }
* def foo = karate.repeat(5, fun)
* karate.forEach(foo, function(item, index){
    match item == expected[index]
})

方法二:使用karate.repeat结合索引校验

* def expected = [1, 1, 1, 6, 8]
* def fun = function(i){ return i * 2 }
* def foo = karate.repeat(5, fun)
* def checkElement = function(index){
    match foo[index] == expected[index]
}
* karate.repeat(foo.length, checkElement)

以上两种方式都会逐个校验每个索引对应的元素,哪怕前面的元素不匹配,后续的对比也会继续执行,所有不匹配的情况都会被逐一报告。

内容的提问来源于stack exchange,提问作者Manish Arya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:25:43