Reputation: 1433
I want to assert a key in the json response.
Response
{
"availableRooms": [
{
"roomId": 2,
"exchangeEmailId": null,
"roomName": "Room 1",
"floor": 0,
"groupID": 3,
"defaultCapacity": 8,
"maxCapacity": 8,
"attributes": [
{
"attributeID": 170,
"displayName": "Video Conference Unit",
"abbreviation": "VCU"
}
],
"externalRoomEmail": "[email protected]"
}
],
"availableRoomsForAllDates": {},
"callResponse": {
"message": null,
"customResponseCode": null
}
}
Groovy
import groovy.json.JsonSlurper
def ResponseMessage = messageExchange.response.responseContent
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
if( jsonSlurper.containsKey( 'externalRoomEmail' ) )
{
log.info 'a'
}
else
{
log.info 'b'
}
Output
Tue Nov 24 20:24:35 IST 2020:INFO:b
Is there any inbuilt method?
If I try jsonSlurper.availableRooms.externalRoomEmail then it gives me null but testcase is passed.
I want that it should break the testcase if key not found.
Upvotes: 0
Views: 164
Reputation: 4482
<edit - just re-read your question, answer adjusted accordingly>
First of all I'm going to call your parsed json json
instead of jsonSlurper
as the slurper is the groovy class used to parse json and it's conceptually confusing to name the data "slurper".
So your problem is that json.availableRooms
returns a list. In other words you would have to use something like:
if(json.availableRooms.first().externalRoomEmail) {
...
} else {
...
}
to check if the first room had an externalRoomEmail
defined.
From there is depends on what you want to do. Let's say that you wanted to see if any of the available rooms had an externalRoomEmail
defined, you would then do something like:
def roomsWithEmails = json.availableRooms.findAll { it.externalRoomEmail }
if (roomsWithEmails) {
roomsWithEmails.each { room ->
println "room ${room.roomName} has external email ${room.externalRoomEmail}"
}
} else { // no rooms with externalRoomEmail
// do something else
}
Upvotes: 1