aaa90210
aaa90210

Reputation: 12093

Set JSON element in SoapUI TestCase request using Groovy script

There seems to be lots of examples to do this for an XML request, the canonical form being something like:

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context);
holder = groovyUtils.getXmlHolder("MyTestStep#Request" );
holder.setNodeValue( "//foo", "bar");
holder.updateProperty();

How can I do that same for a JSON request? There does not seem to be a 'getJsonHolder'.

Upvotes: 2

Views: 5349

Answers (1)

Rao
Rao

Reputation: 21369

There can be multiple ways, I belive. Assuming there is a soapui test case with below steps

  • Groovy Script test step - which is going to set the json request for the next rest step
  • Rest Request test step

For instance, if you have full json request in string format, here is the code snippet that goes into groovy script

def stepName='restStep'
def request = context.testCase.getTestStepByName(stepName).getTestRequest()
def jsonText = '''
{
  "id" : "sample id",
  "name" : "sample name",
  "tags" : [ "sample tags" ],
  "address" : {
    "street" : "sample street",
    "zipcode" : "sample zipcode",
    "city" : "sample city"
  }
}       
'''
request.setRequestContent(jsonText)

Now, try running the groovy step and see the rest test step's request body, the above request is set.

Using Property Expansion: You may also use the Property expansion in the rest request body like shown below. Note that groovy script may not be required as we are not setting value here, instead define a custom test case level property called NAME.

{
   "id": "sample id",
   "name": "${#TestCase#NAME}",
   "tags": ["sample tags"],
   "address":    {
      "street": "sample street",
      "zipcode": "sample zipcode",
      "city": "sample city"
   }
}

You may also create the dynamic request from objects as well if the data is available in object form instead of static data shown in first example.

Upvotes: 2

Related Questions