How to get request body using a groovy script in ReadyAPI
Hi,
The request (getDrafts) I'm testing takes a list of periods and reply with a list of data for those periods.
Request body:
{
"periods" : ["202101","202102"]
}
Response body:
{
"drafts" : [
{
"period" : "202101",
"data" : {
"name" : "Kalle Kula",
"epost" : "kalle@kula.se"
}
},
{
"period" : "202102",
"data" : {
"name" : "Krille Krokodil",
"phone" : "9876543210"
}
}
]
}
I would like to create a script that reads the requested periods from the request body, and for each value verifies that there is an item for that period in the response body. I also want to verify the content of the data-part for each item but first things first π
The problem is I cannot figure out how to get the contents of the request body from my groovy script.
Kind regards,
CamillaR
This can achieved with Script Assertion for your REST Request test step. No separate Groovy Script test step is needed.
You can access the request using
//the following shows the request
log.info context.request
//he following shows the response
log.info context.response
Here you need to define the expected data as well for each period so that the same can be verified from the response.
Please see the following complete script as per data you have provided
//Closure to parse the json text def getJson = { new groovy.json.JsonSlurper().parseText(it) } //Get the periods from request def expectedPeriods = getJson(context.request).periods //You can modify the expected data if needed, this is as per the sample def expectedData = [202101:[name: 'Kalle Kula', epost: 'kalle@kula.se'], 202102: [name: 'Krille Krokodil', phone: '9876543210']] //Get the response parsed def json = getJson(context.response) //Verify if the response has both the periods assert expectedPeriods == json.drafts.period //Loop thru each period of request and get the respective data from response and verify expectedData.keySet().each { period -> log.info "Expected data for ${period}: ${expectedData[period]}" log.info "Actual data for ${period}: ${json.drafts.find{it.period == "$period"}.data}" //Test if they matching assert expectedData[period] == json.drafts.find{it.period == "$period"}.data }
Here you can test it online with fixed data that was provided in the question.
However, the above script assertion shall work for the dynamic response that you receive provided if change the expected data as per your actual data.