Compare 2 JSON responses for duplicate property value
Hi,
I have two JSON responses that will have dynamic nodes on each request, but same structure and properties. I need to identify if a given property has no duplicate values found in both the JSON responses via groovy. Appreciate you help. Thanks
Example below. ID-424 in JSON1 & 2 are matching.
JSON1
{
"Name" : "Name1",
"Age" : "25",
"DateOfBirth" : "01012000",
"ID" : "453"
},
{
"Name" : "Name2",
"Age" : "25",
"DateOfBirth" : "01012000",
"ID" : "424"
}
JSON2
{
"Name" : "Name3",
"Age" : "21",
"DateOfBirth" : "01012000",
"ID" : "424"
},
{
"Name" : "Name4",
"Age" : "25",
"DateOfBirth" : "01012000",
"ID" : "412"
}
- add a script assertion to both the request test steps with the below code
- below script would check the response and makes the test fail if there are duplicate values for "ReferenceNumber" property
Hoping this is what you need, reply back otherwise.
def duplicateRefs = new groovy.json.JsonSlurper().parseText(context.response).ReferenceNumber.countBy{it}.findResults { it.value > 1 ? it.key : null } log.info "${duplicateRefs.size() > 0 ? 'Duplicate reference numbers found :' + duplicateRefs : 'No duplicate reference numbers'}" assert [] == duplicateRefs, "Duplicate references found, ${duplicateRefs}"
Here is the Groovy Script
- Add a groovy script after the second test request step
- Provide correct values step1, and step2
//Update the Request step names below def step1 = 'Name of the Request step1' def step2 = 'Name of the Request step2' //Closure to get the ReferenceNumber from a json of the Given test step def refNumbers = { step -> new groovy.json.JsonSlurper().parseText(context.testCase.testSteps[step].getPropertyValue('response')).ReferenceNumber } def list1 = refNumbers(step1) def list2 = refNumbers(step2) log.info "Reference Numbers for ${step1} are => ${list1}" log.info "Reference Numbers for ${step2} are => ${list2}" assert list1.every { !list2.contains(it) }, 'Does not match the expected result'
-