I have a json Request like this:
{
"scopeId":"",
"scopeType":"",
"userId":"",
"fieldToBeEncryptedList":[
{
"srNo":"",
"fieldName":"",
"value":"",
"echoField":""
}
]
}
Now what I want is to set the value of each key dynamically which I got from response of other Test Step. How could I do this using groovy scripting.
Thanks in Advance.
Some details are missing in your question, but I suppose that you have two REST TestSteps
, supposing that the first is called REST Test Request
and the second REST Test Request2
you can set the response and get request values for your testSteps using the follow groovy script inside a groovy TestStep
:
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
// request
def request = '''{"scopeId":"",
"scopeType":"",
"userId":"",
"fieldToBeEncryptedList":[{"srNo":"","fieldName":"","value":"","echoField":""}]
}'''
// parse the request
def jsonReq = new JsonSlurper().parseText(request);
// get the response where you've the values you want to get
// using the name of your test step
def response = context.expand('${REST Test Request#Response}')
// parse response
def jsonResp = new JsonSlurper().parseText(response)
// get the values from your first test response
// and set it in the request of the second test
jsonReq.scopeId = jsonResp.someField
jsonReq.scopeType = jsonResp.someObject.someField
// ...
// parse json to string in order to save it as a property
def jsonReqAsString = JsonOutput.toJson(jsonReq)
// save as request for the next testStep
def restRequest = testRunner.testCase.getTestStepByName('REST Test Request2');
restRequest.setPropertyValue('Request',jsonReqAsString);
This scripts gets your json and fill it with the values from the first testStep
response, and then set this json as a request for the second testStep
.
Hope this helps,
You may have to do something like this:
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def jsonStr = '{"scopeId":" ","scopeType":" ","userId":" ","fieldToBeEncryptedList":[{"srNo":" ","fieldName":" ","value":" ","echoField":" "}]}'
def slurp = new JsonSlurper().parseText(jsonStr)
def builder = new JsonBuilder(slurp)
builder.content.scopeId = 'val1'
builder.content.fieldToBeEncryptedList[0].srNo = 'val2'
println builder.toPrettyString()
Output:
{
"fieldToBeEncryptedList": [
{
"echoField": " ",
"fieldName": " ",
"srNo": "val2",
"value": " "
}
],
"scopeId": "val1",
"scopeType": " ",
"userId": " "
}