Asserting and using conditions for an array response in Karate

烈酒焚心 提交于 2021-02-13 12:42:56

问题


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": "",
                    }
                ]
            }
        }, 
     ]
}

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
   }
}

How could I achieve something similar in Karate? Should I use a Java Helper?


回答1:


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(_)'

Here's another example: https://stackoverflow.com/a/62567412/143475

There are other ways to loop in Karate, but not really designed for matching: https://github.com/intuit/karate#loops

Here's an extreme example involving JSON transformation to make it easier to match: https://stackoverflow.com/a/53120851/143475

Also refer: https://github.com/intuit/karate#conditional-logic



来源:https://stackoverflow.com/questions/62566219/asserting-and-using-conditions-for-an-array-response-in-karate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!