在空手道中断言和使用数组响应的条件
Asserting and using conditions for an array response in Karate
我收到一个请求,要求 returns 根据 'status'.
的两种可能结构的响应列表
{
"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": "",
}
]
}
},
]
}
我需要检查状态为 'Receipted' 或 'Failed' 的结构。在 Java 中,我会使用 for 循环和其中的 if 语句来根据 'status' 字段检查具有不同标准的响应字段。 (示例如下)
for (int i = 0; i < response.length; i++){
if (response[i].status.equals("receipted")){
//do something
}
else{ //failed
//do something else
}
}
我怎样才能在空手道中达到类似的效果?我应该使用 Java 助手吗?
首先,我们鼓励您在测试中编写静态预期结果。也就是说有多种方法可以做到这一点,这里是一个:
* 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://github.com/intuit/karate#loops
这里有一个极端的例子,涉及 JSON 转换以使其更容易匹配:
我收到一个请求,要求 returns 根据 'status'.
的两种可能结构的响应列表{
"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": "",
}
]
}
},
]
}
我需要检查状态为 'Receipted' 或 'Failed' 的结构。在 Java 中,我会使用 for 循环和其中的 if 语句来根据 'status' 字段检查具有不同标准的响应字段。 (示例如下)
for (int i = 0; i < response.length; i++){
if (response[i].status.equals("receipted")){
//do something
}
else{ //failed
//do something else
}
}
我怎样才能在空手道中达到类似的效果?我应该使用 Java 助手吗?
首先,我们鼓励您在测试中编写静态预期结果。也就是说有多种方法可以做到这一点,这里是一个:
* 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://github.com/intuit/karate#loops
这里有一个极端的例子,涉及 JSON 转换以使其更容易匹配: