How to compare 2 JSON objects containing array using Karate tool

Viewed 3474

One of the API testing using intuit/karate,

Expected JSON is: {name: hello, config:[{username: abc, password: xyz},{username: qwe, password: tyu}]}

There is two possibility of an API response.

First possible actual JSON: {name: hello, config:[{username: qwe, password: tyu},{username: abc, password: xyz}]}

Second possible actual JSON: {name: hello, config:[{username: abc, password: xyz},{username: qwe, password: tyu}]}

Likewise, the sequence of array element is different in actual response, hence following approach of validation of response throws error randomly.

  • And response == < ExpectedResponse >
  • And response contains < ExpectedResponse >

Sometimes error is thrown as : Error : { Actual: response.config[0].abc, Expected: response.config[0].qwe }

Sometimes error is thrown as : Error : { Actual: response.config[0].qwe, Expected: response.config[0].abc }

Would you please provide exact karate approach of JSON validation in which entire JSON along with ignore the sequence of element in JSON containing array ?

1 Answers

Here is the solution:

* def response1 = {name: 'hello', config:[{username: 'qwe', password: 'tyu'},{username: 'abc', password: 'xyz'}]}
* def response2 = {name: 'hello', config:[{username: 'abc', password: 'xyz'},{username: 'qwe', password: 'tyu'}]}

* def config = [{username: 'qwe', password: 'tyu'},{username: 'abc', password: 'xyz'}]
* match response1 == { name: 'hello', config: '#(config)' }
* match response2 == { name: 'hello', config: '#(^^config)' }
Related