这是我对特定请求的答复
{
"data": {
"foo": [{
"total_value":200,
"applied_value": [{
"type": "A",
"id": 79806,
"value": 200
}]
}]
}
}
这是我对 SAME 请求
的另一个答复{
"data": {
"foo": [{
"total_value":300,
"applied_value": [{
"type": "A",
"id": 79806,
"value": 200
},
{
"type": "B",
"id": 79809,
"value": 100
}
]
}]
}
}
我不确定我会针对哪种情况做出回应 所以用例是 每当 applied_value 中有2个值时,添加两个值并声明 每当 applied_value 中只有1个值时,直接声明
答案 0 :(得分:1)
这是一种可能的解决方案:
* def adder = function(array) { var total = 0; for (var i = 0; i < array.length; i++) total += array[i]; return total }
* def response =
"""
{
"data": {
"foo": [{
"total_value":300,
"applied_value": [{
"type": "A",
"id": 79806,
"value": 200
},
{
"type": "B",
"id": 79809,
"value": 100
}
]
}]
}
}
"""
* def expected = get[0] response..total_value
* def values = $response..value
* def total = adder(values)
* match expected == total
仅作为示例,实现adder
例程的另一种方法是这样的:
* def total = 0
* def add = function(x){ karate.set('total', karate.get('total') + x ) }
* eval karate.forEach(values, add)