空手道 - 验证整个json响应的模式

问题描述 投票:1回答:2

我正在使用Karate验证GET请求的整个json响应。

以下是来自请求的示例json响应(我只显示了两个项目元素)

[
  {
    "items": [
      {
        "createdById": "ADMIN",
        "createdByName": "ADMIN",
        "changedByName": "ADMIN",
        "oid": "121212fgfg2123",
        "links": {
          "self": {
            "href": "/internal/organiz/12345"
          },
          "subcom": []
        },
        "name": "NewETLTesting"
      },
      {
        "createdById": "ADMIN",
        "createdByName": "ADMIN",
        "changedByName": "ADMIN",
        "oid": "1212dfffg45",
        "links": {
          "self": {
            "href": "/internal/organiz/5a6e0"
          },
          "subcom": []
        },
        "name": "FromKarateModified"
      }
    ]
  }
]

以下是我尝试验证的方法:

 And match response.*.* ==
    """
  {
    "createdById" : '#string',
    "createdByName" : '#string',
    "changedByName" : '#string',
    "oid" : '#string',
    "links" : '#object',
    "name" : '#string'
  }
    """

但是,我得到一个断言错误:reason: actual value is not map-like。如果我尝试在花括号周围放置方括号,我会得到reason: actual and expected arrays are not the same size。此外,我试图像$.[*].等响应,但无法让它工作。

提前致谢!!

karate
2个回答
2
投票

您需要注意您的JSON结构并更好地理解JsonPath。您可以剪切并粘贴以下内容并查看其工作情况:

* def response = 
"""
[
  {
    "items": [
      {
        "createdById": "ADMIN",
        "createdByName": "ADMIN",
        "changedByName": "ADMIN",
        "oid": "121212fgfg2123",
        "links": {
          "self": {
            "href": "/internal/organiz/12345"
          },
          "subcom": []
        },
        "name": "NewETLTesting"
      },
      {
        "createdById": "ADMIN",
        "createdByName": "ADMIN",
        "changedByName": "ADMIN",
        "oid": "1212dfffg45",
        "links": {
          "self": {
            "href": "/internal/organiz/5a6e0"
          },
          "subcom": []
        },
        "name": "FromKarateModified"
      }
    ]
  }
]
"""
And match each response[0].items ==
"""
  {
    "createdById" : '#string',
    "createdByName" : '#string',
    "changedByName" : '#string',
    "oid" : '#string',
    "links" : '#object',
    "name" : '#string'
  }
"""

0
投票

以下Schema将正确验证整个响应

* def refSubcom = {<object schema>}
* def refself = {href : '#string'}
* def refLinks = {self : '#object refself', subcom:'##[] refSubcom'}
* def optionalItemArr = 
    """
    {
        createdById:'#string',
        createdByName:'#string',
        changedByName:'#string',
        oid: '#string',
        links: '#object refLinks',
        name:'#string'
    }
    ###
* def itemData = 
    """
    {
        item : '##[] optionalItemArr'
    }
    """
* def reponseSchema = '##object itemData'

* def SuccessSchema = '##[] reponseSchema'

你可以参考以下链接:karate : Complex JSON Schema matching

© www.soinside.com 2019 - 2024. All rights reserved.