首页 > 解决方案 > 如何从 json 文件中读取请求负载中的动态数据?

问题描述

下面是我的示例JSON文件,命名为multiple.json,我给出了我的 json 文件的示例结构。

{
    "sample_key":[{"name":"John","salary":"10000","age":"25"}],
    "another_key":[{"author":"Scott","publication":"Pearson","year":"2019"}]
}

我有一个功能文件,其中有两个Scenario Outline. 该文件正在从包含由键值对分隔的不同对象的文件中读取JSON对象。我想传递is和下面的功能文件中的数据。multiple.jsonJSONrequest payloadsample_keyanother_key

我的Sample.feature文件:

Background:
    * def kittens = read('../json/multiple.json')

Scenario Outline: Create Sample Name Record
Given url url
And request { sample_key:'<sample_key>'}        // Here, I have question..
When method POST
Then status 200
* def output = response
* print output

Examples:
|kittens|

Scenario Outline: Create Sample Author Record
Given url url
And request { another_key:'<another_key>'}      // Here, I have question..
When method POST
Then status 200
* def output = response
* print output

Examples:
|kittens|

但是,它只能在下面JSON使用scenario。(这里,我没有添加JSON object in array

{ "sample_key":{"name":"John","salary":"10000","age":"25"}, "another_key":{"author":"Scott","publication":"Pearson","year":"2019"} }

但是当我给出时它不起作用JSON object in array(如问题顶部所述)

我想在一个中传递多个记录sample_key,我想在一个中运行它scenario

那么,我怎样才能通过sample_key in Scenario Outline: Create Sample Name Record呢?

请建议我。谢谢 !!

标签: jsonkaratedata-driven-tests

解决方案


编辑:也许这是您正在寻找的答案:

Examples:
| kittens.sample_key |

也许你不需要Scenario Outlinethen 。您可以按索引访问 JSON,只需使用 2 Scenario-s

* def sample_key = kittens.sample_key[0]

另请注意,如果您使用动态Scenario Outline,则会得到一个自动__num变量:https ://github.com/intuit/karate#scenario-outline-enhancements

因此,如果 kittens 是 JSON 数组,您可以这样做:

* def payload = kittens[__num]

推荐阅读