我有一个请求,它返回两种可能结构的响应列表,具体取决于“状态”。
{
"listSize": 2,
"itemList": [
{
"id": ,
"Name": "",
"submittedOn": "",
"Reference": null,
"status": "Receipted",
"response": null
},
{
"id": 12345,
"submittedOn": "",
"Reference": null,
"status": "Failed",
"response": {
"xml": "",
"formErrors": [
{
"error_type": "",
"error_location":"",
"error_message": "",
}
]
}
},
]
}
我需要检查状态“已收到”或“失败”的结构。在 Java 中,我将使用 for 循环和其中的 if 语句来根据“状态”字段使用不同的条件检查响应字段。 (如下例)
for (int i = 0; i < response.length; i++){
if (response[i].status.equals("receipted")){
//do something
}
else{ //failed
//do something else
}
}
我怎样才能在空手道中实现类似的目标?我应该使用 Java Helper 吗?
首先,鼓励您在测试中编写静态预期结果。也就是说,有多种方法可以做到这一点,这是一种:
* def failedSchema = { xml: '#string', formErrors: '#array' }
* def isValid = function(x){ if (x.status == 'Receipted') return x.response == null; return karate.match(x.response, failedSchema).pass }
* match each response.itemList == '#? isValid(_)'
这是另一个例子:https://stackoverflow.com/a/62567412/143475
空手道还有其他循环方式,但并不是真正为匹配而设计的:https://github.com/intuit/karate#loops
这是一个涉及 JSON 转换的极端示例,以使其更容易匹配:https://stackoverflow.com/a/53120851/143475
另请参阅:https://github.com/intuit/karate#conditional-logic | https://stackoverflow.com/a/76091034/143475