Ask a Question

How to assert a JSON response which have results in random order everytime ?

Swami
New Member

How to assert a JSON response which have results in random order everytime ?

For exmaple: Response for GET /cat/cat-123/contains/kitten

 

{
"action": "get",
"status": "200",
"entities": [
{
"type": "kitten",
"created": 1472669778713,
"modified": 1472669778713,
"alias": "kitten-1",
"name": "kitten-1"
},
{
"type": "kitten",
"created": 1472669781833,
"modified": 1472669781833,
"alias": "kitten-2",
"name": "kitten-2"
}
]
}

 

Here the response will randomly order kitten-1 and kitten-2 for every GET on this. if I add a JSONPath Match aessrtion $.entities[0].alias = kitten-1 and $.entities[1].alias = kitten-2, it will be PASS now. But it will fail in my next attempt of execution as the value will randonly change and it will become kitten-2 and kitten-1 in order.

 

How I can add a assertion that the "alias" attribute in response can either be  kitten-1 or kitten-2 ??

2 REPLIES 2
tgeliot
Contributor

If all else fails you can write a Groovy Script step that plucks these values out of this step's response and looks at each one.  To make this easier, Ready!API provides a "Get Data" feature that's pretty slick.  To use it, first run your test step that gets this JSON response.  Then create a Groovy Script test step, and in the text field for that, right click, and select "Get Data".  Then just follow the menus to the value you want.

nmrao
Community Hero

Not familiar with JsonPath.

 

However, below Script Assertion should help you achieve the same.

 

 

import groovy.json.JsonSlurper
//Here defined the expected list def expectedList = ['kitten-1', 'kitten-2'] ​​​​def json = ​new JsonSlurper().parseText(context.response)
//The result is sorted in the below statement def actualList = json.entities.alias.sort()
//Hence, order should not matter for asserting the response. assert actualList == expectedList​, "Response alias names don't match"

 



Regards,
Rao.
cancel
Showing results for 
Search instead for 
Did you mean: