断言和使用空手道中数组响应的条件 [英] Asserting and using conditions for an array response in Karate
问题描述
我收到一个请求,它根据状态"以两种可能的结构返回响应列表.
I've got a request that returns a list of responses in two possible structures, depending on the '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": "",
}
]
}
},
]
}
我需要检查已接收"或失败"状态的结构.在 Java 中,我将使用 for 循环和其中的 if 语句根据状态"字段检查具有不同标准的响应字段.(示例如下)
I need to check the structure for the status being either 'Receipted' or 'Failed'. In Java I would use a for loop and an if statement within it to check the response field with different criteria depending on the 'status' field. (Example below)
for (int i = 0; i < response.length; i++){
if (response[i].status.equals("receipted")){
//do something
}
else{ //failed
//do something else
}
}
我怎样才能在空手道中取得类似的成绩?我应该使用 Java Helper 吗?
How could I achieve something similar in Karate? Should I use a Java Helper?
推荐答案
首先,我们鼓励您在测试中编写静态的预期结果.也就是说有多种方法可以做到这一点,这里是一种:
First, you are encouraged to write static expected results in tests. That said there are multiple ways to do this, here's one:
* 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
There are other ways to loop in Karate, but not really designed for matching: https://github.com/intuit/karate#loops
这是一个涉及 JSON 转换以使其更易于匹配的极端示例:https://stackoverflow.com/a/53120851/143475
Here's an extreme example involving JSON transformation to make it easier to match: https://stackoverflow.com/a/53120851/143475
另请参考:https://github.com/intuit/karate#conditional-logic
这篇关于断言和使用空手道中数组响应的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!