1

Here is my script:

  Scenario Outline: Test
* def body = {}
* set body
  | path           | value   |
  | name           | <name>  |
  | metadata.<key> | <value> |

Given url 'http://localhost/'
* request body
When method post

Examples:
  | name   | key    | value    |
  | 'John' | 'key1' | 'value1' |
  | 'Jane' |        |          |

When I post the request I get the body as:

{"name": "John", "metadata": {"'key1'": "value1"}}

How do I get the metadata.key to be "key1"?

BigKev
  • 11
  • 2

1 Answers1

0

It is simpler than you think:

Scenario Outline: Test
* def body = { name: '#(name)' }
* body[key] = value

* print body

Examples:
  | name | key  | value  |
  | John | key1 | value1 |
  | Jane | key2 | value2 |

Also refer: https://github.com/intuit/karate#scenario-outline-enhancements

EDIT: if you really have wildly different payloads in each row, I personally recommend you create a separate Scenario - in my opinion, trying to squeeze everything into a single super-generic-dynamic Scenario just leads to readability and maintainability issues, refer: https://stackoverflow.com/a/54126724/143475

That said, you can do this:

Scenario Outline: Test
* print body

Examples:
  | body!                                                |
  | { "name": "John", "metadata": { "key1": "value1" } } |
  | { "name": "Jane" }                                   |

There are "smart" ways to remove some parts of a JSON like this: https://github.com/intuit/karate#remove-if-null - but you can choose which approach is simpler.

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • OK - I've fixed my table to better reflect what I want to do: The first record POST body should be: `{ "name": "John", "metadata": { "key1": "value1" }` while the second record POST body should be: `{ "name": "Jane" }` The actual JSON object that I'm dealing with has about 8 different fields of which only 3 are mandatory. If just seemed the body structure that I'm using fits what I need to do. – BigKev Mar 03 '20 at 04:26
  • Having a bit more of a play with it, I can get around the issue with this `Scenario Outline: Test2 * def body = {} * set body | path | value | | name | | | metadata | | * print body Examples: | name | value | | 'John' | {"key1":"value1"} | | 'Jane' | |` As mentioned earlier, I have 8 fields of which only three are mandatory and this metadata field is the only one giving me any issues. That's also why I would prefer to keep it all together. – BigKev Mar 04 '20 at 00:54