本文介绍了空手道API json响应-如何验证有时会出现但有时不在API响应中的键的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助来验证响应中是否存在一个键. API的响应类似于-

I need help in validating the presence of one key in the response. The response of the API looks like -

"persons": [
        {
            "id": "27",
            "source": {
                "personId": 281,
                "emailAddress": "[email protected]",
                "firstName": "Steve"
            }
        },
        {
            "id": "28",
            "source": {
                "personId": 353,
                "emailAddress": "[email protected]",
                "firstName": "John"
                "LastName" : "Cena"
            }
        }
    ]
}

我想断言 source.LastName 是否出现,如果出现,则它应该始终包含字符串值.

I want to assert if the source.LastName appears or not and if it does then it should always hold a string value.

该解决方案应该是通用的,并且应该可以在30或40人的对象下工作,目前我使用的是空手道版本0.9.4,并且需要解决此类情况的解决方案.

The solution should be generic and it should work for 30 or 40 persons object also down the time, currently I am using karate version 0.9.4 and need a resolution for handling such scenarios.

提前谢谢!

推荐答案

在架构中"##string"验证字段可以为null还是字符串.

In the schema "##string" validates that the field can be null or a string.

示例代码:

Feature: Schema validation

    Scenario:
        * def resp =
            """
            {
            "persons": [
                    {
                        "id": "27",
                        "source": {
                            "personId": 281,
                            "emailAddress": "[email protected]",
                            "firstName": "Steve"
                        }
                    },
                    {
                        "id": "28",
                        "source": {
                            "personId": 353,
                            "emailAddress": "[email protected]",
                            "firstName": "John",
                            "LastName" : "Cena"
                        }
                    }
                ]
            }
            """
        * def schema =
        """
            {
                "id": "#string",
                "source": {
                    "personId": "#number",
                    "emailAddress": "#string",
                    "firstName": "#string",
                    "LastName": "##string"
                }
            }

        """
        * match each resp.persons == schema

这篇关于空手道API json响应-如何验证有时会出现但有时不在API响应中的键的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:10