Forum Discussion

livetoski78's avatar
livetoski78
New Contributor
6 years ago
Solved

How to set the value of a test case property from JSON response via Groovy?

I'm using SoapUI open source for REST testing, so I need to do things the hard way via Groovy (no JSON property transfer).  I have a test step that places a call to /workspaces, creating a new workspace object and returns an id for said object in the response under data[0].id.  I'm using JsonSlurper to parse the response and can easily run asserts on the parsed response.  Where I'm having trouble, is figuring out how to set a test case property so that I can pass the id into the endpoint of the next response in the test case, a PUT to /workspaces/{workspace.id}.  Here's what I have so far in a Groovy script test step between the two:

import groovy.json.JsonSlurper

def responseJson = testRunner.testCase.getTestStepByName("Create Workspace").getPropertyValue("response")
def slurper = new JsonSlurper().parseText(responseJson)

def testCaseProperty = testRunner.testCase.getPropertyValue("workspace_id")
testRunner.testCase.setPropertyValue("workspace_id", slurper.data[0].id)

This returns the following error message:

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer error at line: 7

 

A little help please?

  • nmrao's avatar
    nmrao
    6 years ago

     

    livetoski78 ,

    Please use below script assertion to the REST Request Test step( that means remove the additional groovy script test step)

     

    /**
    * Below is the script assertion for the REST Request step
    * which extracts the data id and set it test case property
    **/
    assert context.response, 'Response is empty or null'
    def json = new groovy.json.JsonSlurper().parseText(context.response)
    //Change the property name as needed
    log.info json.data.id
    context.testCase.setPropertyValue('ID', json.data.id.toString())

6 Replies

  • nmrao's avatar
    nmrao
    Champion Level 3
    Change below of the last statement
    From:
    slurper.data[0].id

    To:
    slurper.data[0].id as String
    • livetoski78's avatar
      livetoski78
      New Contributor

      I changed the last line to:

      testRunner.testCase.setPropertyValue("workspace_id", slurper.data[0].id as String)

      But am still receiving the same error.

      • nmrao's avatar
        nmrao
        Champion Level 3
        Can you please post the json?