为空手道中的数组响应声明和使用条件 [英] 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屋!