首页 > 解决方案 > 如何使用 yml 文件验证空手道结构响应

问题描述

最近我第一次开始使用空手道和 Yaml。我能够验证所有答案数据都在同一级别上的简单响应结构。但是现在我必须验证一个更复杂的结构,我花了很多时间都没有成功。

当我执行 GET 请求时,我收到下一个答案:

[
    {
        "factories": [
            {
                "id": 1,
                "scopes": [
                    {
                        "id": null,
                        "name": "name 1",
                        "expireD": 10,
                        "isExpired": true
                    }
                ],
                "companyName": "TEST",
            },
            {
                "id": 2,
                "scopes": [
                    {
                        "id": null,
                        "name": "name 2",
                        "expireD": 7,
                        "isExpired": true
                    }
                ],
                "companyName": "TEST2",
            }
        ],
        "scopeId": null
    }
]

结构验证不直接在空手道代码中。它位于这样的 yml 文件中:

operationId: getTest
statusCode: 200
params:
body: null
matchResponse: true
responseMatches:
  scopeId: '##number'
  factories:
    companyName: '#string'
    id: '#number'
    scopes:
      expireD: '#number'
      name: '#string'
      id: '#null'
      isExpired: '#boolean'

我检查了大约 100 次结构,当我到达这里时,我总是遇到同样的错误:

* match response contains responseMatches

错误是下一个: $[1].factories | 数据类型不匹配 (LIST:MAP)

我尝试使用 match each,一个一个地忽略结构以查看哪个结构失败,并将验证减少为 #array 并且它不起作用。

任何帮助都将受到欢迎。谢谢你。

标签: yamlcucumberkarate

解决方案


我真的建议不要使用 YAML,尤其是在测试/验证场景中。但最后是你的电话。

这是一个可以节省您一些时间的提示,您可以打印出 YAML 的值并查看哪里出错了。我不知道 YAML(并尽可能避免它),但在几次失败的尝试后我做了一个猜测,并设法-在正确的位置插入 a(显然还有很多其他方法)以使一些 YAML JSON 数组 - 这就是你想要的。

* text foo =
"""
operationId: getTest
statusCode: 200
params:
body: null
matchResponse: true
responseMatches:
  scopeId: '##number'
  factories:
    -
      companyName: '#string'
      id: '#number'
      scopes:
        expireD: '#number'
        name: '#string'
        id: '#null'
        isExpired: '#boolean'
"""
* yaml foo = foo
* print foo

尝试上述方法,看看它与您的示例有何不同。


推荐阅读