首页 > 解决方案 > 如何在空手道特定的 json 模式中使用模板

问题描述

我在空手道下面尝试。

我在 .json 文件中有一个 json 模式(用于响应验证)。在许多模式中,很少有常见的 REGEX。我想将它们作为键值对提取到一个通用文件中,并在其他模式中使用它。可能吗?如果是这样,我该怎么做?json 模式中是否允许模板化?

例子:

示例 Json 架构文件 (sample-response.json):

{
  "response": {
    "name": "#string",
    "amount": "#regex ^(-?)([0]|[1-9][0-9]{0,15})[.][0-9]{2}$"
  }
}

特征文件

Feature: Example feature

  Background:

  * def sampleResponse = read('./sample-response.json');



  Scenario: Example scenario

    When url 'https://someurl.com'
    And method get
    Then status 200
    And  match response == sampleResponse

我想做什么?

我想将数量正则表达式存储在 json 文件中作为可重用变量,并使用 json 文件中的模板来替换它。可能吗?


{
  "response": {
    "name": "#string",
    "amount": "{{get regex from this template}}"
  }
}

标签: jsonschemakarate

解决方案


是的。嵌入式表达式即使在读取文件时也能正常工作。

所以这样做:

{
  "response": {
    "name": "#string",
    "amount": "#(amount)"
  }
}

然后这样做:

Background:
* def amount = 100
* def sampleResponse = read('sample-response.json')

如果您希望amount来自另一个 JSON 文件,为什么不呢,请说以下内容data.json

{ "amount": 100 }

然后你这样做:

Background:
* def data = read('data.json')
# you don't need the next line if you use "data.amount" as the embedded expression
* def amount = data.amount
* def sampleResponse = read('sample-response.json')

推荐阅读