Aditya Mukesh
Aditya Mukesh

Reputation: 92

How do i give a dynamic key for schema assertion in karate DSL

I want to match my response by adding a variable in the schema assertion. I tried it by giving '#(value)' but it did not work

 * def value = 3

    Then match object ==
    {
         result : {
                      '#(value)'
                               {
                                  firstName : '#string',
                                  lastName : '#string'
                               }
                    }
    }

The exception i'm getting says 'path $.result.(#value) actual : null expected { firstName : '#string' lastName : '#string' }'

Upvotes: 2

Views: 1397

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58088

There's something terribly wrong with your JSON. Are you really trying to use a dynamic key ? That's not possible.

Here's a working example that may help you figure out what you are doing wrong:

* def actual = { result: { value: 3, foo: { firstName: 'John', lastName: 'Smith' } } }
* def value = 3
Then match actual ==
"""
{
  result : {
    value: '#(value)',
    foo: {
      firstName : '#string',
      lastName : '#string'
    }
  }
}
"""

(edit:) looks like the ask was indeed for a dynamic key, here is a changed example:

* def actual = { result: { 3: { firstName: 'John', lastName: 'Smith' } } }
* def fun =
"""
function(key) {
  var temp = { result: {} };
  temp.result[key] = { firstName: '#string', lastName: '#string' };
  return temp;
}
"""
Then match actual == fun(3)

Upvotes: 3

Related Questions