how to dynamically set an value in json read from file in Karate

一曲冷凌霜 提交于 2021-02-16 14:42:32

问题


I want to dynamically set value for some elements in JSON(read from a file) using data driven feature of KARATE framework. Here are more details:

request.json -> { wheels : <wheel>, color: '<color>' }

Feature: Read json input from file and iterate over data table values

Background:

* url ''
* def reqJson = read('request.json') 
* print reqJson

Scenario Outline: Test file read

# I want to avoid writing below set statements for each element in request
#* set reqJson.wheels = <wheel>
#* set reqJson.color = '<color>'

Given path ''
And request reqJson
When method POST
Then status 200
And match response contains {mode: '<result>'}

Examples:

| wheel | color | result  |
| 4     | red   | car     |
| 2     | any   | bicycle | 

I am developing automation framework using Karate, my intention is to save sample request in JSON file for a given API and then during execution I want element values to be replaced with the ones given in the table above.I don't want to write set statement for each element either(commented lines above)

P.S.: I tried with calling other feature file using table approach. However, I want to keep one feature file per API, hence want to know if there is any way possible for the above approach


回答1:


I think you have missed embedded expressions which is simpler than the set keyword in many cases, especially when reading from files.

For example:

request.json -> { wheels : '#(wheels)', color: '#(color)' }

And then this would work:

* def wheels = 4
* def color = 'blue'
* def reqJson = read('request.json')
* match reqJson == { wheels: 4, color: 'blue' }

If you go through the demo examples you will get plenty of other ideas. For example:

* table rows
| wheels | color  | result |
|      4 | 'blue' | 'car'  |
|      2 | 'red'  | 'bike' |

* call read('make-request.feature') rows

And where make-request.feature is:

Given path ''
And request { wheels: '#(wheels)', color: '#(color)' }
When method POST
Then status 200
And match response contains { mode: '#(result)' }


来源:https://stackoverflow.com/questions/50088250/how-to-dynamically-set-an-value-in-json-read-from-file-in-karate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!