protea protea - 13 days ago 10
Groovy Question

Assert response starts with

I am trying to assert the response, to check if the response value starts with a certain text. I tried using the function

startsWith
but it seems like it does not work in SOPAUI script assertion.

This is what I have tried:

import groovy.json.JsonSlurper

//grab the response
def ResponseMessage = messageExchange.response.responseContent.records
//define a JsonSlurper
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
//log.info jsonSlurper

assert jsonSlurper.startsWith("Text")


Here is the json response

{
"Name": "Natalie",
"message": "What are you doing"
}


I want to check if the
Name
starts with "Nat"

Answer

From documentation JsonSlurper().parseText(String text) returns:

data structure of lists and maps

so you can not use startsWith directly. To achieve what you want you have to go to the desired object in the path and use startsWith there. Something like must works for your case:

import groovy.json.JsonSlurper    

def jsonStr = '{ "Name": "Natalie", "message": "What are you doing" }'

def jsonSlurper = new JsonSlurper().parseText(jsonStr)
assert jsonSlurper.Name.startsWith("Nat")