我想使用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()
尽管这似乎可以按预期工作,但它很难看。有没有更好的方法来测试阵列的顺序?
是的!如果仅将数字提取到数组中,则变得很简单-它在后台只是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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句