user3089045
user3089045

Reputation: 199

SoapUi Assertions - Use a string as a json path with groovy

I am using groovy to automate some tests on SoapUI, and I wanted to also automate assertions in a way I would get a field's name and value from a *.txt file and check if the wanted field does exist with the wanted value in the SOapUI response.

Suppose I have the following json response:

{
   "path" : {
         "field" : "My Wanted Value"
    }
}

And from my text file I would have the following two strings :

path="path.field"
value="My Wanted Value"

I tried the following :

import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText response

assert json.path==value;

But of course it doesn't work.

Any idea how can I get it done please?

Thank you

Upvotes: 1

Views: 3363

Answers (1)

albciff
albciff

Reputation: 18507

I think your problem is to access a json value from a path based with . notation, in your case path.field to solve this you can use the follow approach:

import groovy.json.JsonSlurper

def path='path.field'
def value='My Wanted Value'
def response = '''{
   "path" : {
         "field" : "My Wanted Value"
    }
}'''

def json = new JsonSlurper().parseText response

// split the path an iterate over it step by step to 
// find your value
path.split("\\.").each {
  json = json[it]
}

assert json == value

println json // My Wanted Value
println value // My Wanted Value

Additionally I'm not sure if you're also asking how to read the values from a file, if it's also a requirement you can use ConfigSlurper to do so supposing you've a file called myProps.txt with your content:

path="path.field"
value="My Wanted Value"

You can access it using the follow approach:

import groovy.util.ConfigSlurper

def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
println config.path // path.field
println config.value // My Wanted Value

All together (json path + read config from file):

import groovy.json.JsonSlurper
import groovy.util.ConfigSlurper

def response = '''{
   "path" : {
         "field" : "My Wanted Value"
    }
}'''

// get the properties from the config file
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
def path=config.path
def value=config.value

def json = new JsonSlurper().parseText response

// split the path an iterate over it step by step
// to find your value
path.split("\\.").each {
 json = json[it]
}

assert json == value

println json // My Wanted Value
println value // My Wanted Value

Hope this helps,

Upvotes: 2

Related Questions