I have an API to save employee details to DB and I post the data using an HTTP POST API "/empDetails" and I post the details like "emp_name", "emp_id" and "emp_age"
Sample Payload,
{
"emp_name": "Sam",
"emp_age": "25",
"emp_id": "M33214"
}
Once the data is successfully stored, I would invoke the GET "/empDetails" API to read the posted employee details.
Now I want to verify the returned data. Sometimes the returned order might be jumbled. How can I verify the data using any custom assertions with the help of any language like JavaScript or Groovy or BeanShell?
P.S: I can add text response contains and can compare key-value pair. But when the key-value pair count is more it would be difficult to add the assertion all the time. ex: the current payload have only 3 key-value pair, the sample payload may have additional fields too like "empReportingManager", "empAccount" etc..
Here the Post payload is read from a file using __FileToString() method.
Thanks in advance.
Regards, Hari
GET
requestPut the following code into "Script" area:
def actual = new groovy.json.JsonSlurper().parseText(sampleResult.getResponseDataAsString())
def expected = new groovy.json.JsonSlurper().parseText(new File('/path/to/request.json').text)
if (actual != expected) {
assertionResult.setFailureMessage(true)
assertionResult.setFailureMessage('Mismatch between received and sent JSON')
}
If JSON payload will match response (order does not really matter) the sampler will pass, otherwise you will get Mismatch between received and sent JSON
message and the sampler will be marked as failed.
Check out Scripting JMeter Assertions in Groovy - A Tutorial article for more details.
Note: for more complex JSON structures, i.e. if there are nested JSON Arrays it's better to go for JSONAssert library.