我想使用Karate根据对象中的字段测试从端点返回的数组是否处于特定顺序。例如,我可能有如下数据:
[
{ seconds: 20 },
{ seconds: 15 },
{ seconds: 12 }
]
我的目标是测试对象按降序列出。
我已经成功完成了此测试,但我正在寻找一种更好的方法来进行测试。这是我测试订单的方法:
* def orderTest = function() { for(var i = 0; i < response.length; i++) { if(i !== 0 && response[i].seconds > response[i-1].seconds) return false; } return true; }
Then assert orderTest()
这似乎可以按预期工作,但它是 丑陋 。有没有更好的方法来测试数组的顺序?
答案 0 :(得分:4)
是的!如果仅将数字提取到一个数组中就变得很简单-它在后台只是Java List
,因此可以在其上应用Collections
方法:
* def Collections = Java.type('java.util.Collections')
* def response =
"""
[
{ seconds: 20 },
{ seconds: 15 },
{ seconds: 12 }
]
"""
* def before = $response[*].seconds
* copy after = before
* Collections.sort(after, Collections.reverseOrder())
* match before == after