如何在soapUI中将json对象的值设置为Request

时间:2015-07-01 12:01:02

标签: json rest groovy soapui

我有一个像这样的json请求:

{
    "scopeId":"",
    "scopeType":"",
    "userId":"",
    "fieldToBeEncryptedList":[
    {
    "srNo":"",
    "fieldName":"",
    "value":"",
    "echoField":""
    }
]
}

现在我想要的是动态设置每个键的值,这是我从其他测试步骤的响应中得到的。我怎么能用groovy脚本来做这件事。

先谢谢。

2 个答案:

答案 0 :(得分:5)

您的问题中缺少一些详细信息,但我认为您有两个REST TestSteps,假设第一个被称为REST Test Request而第二个REST Test Request2您可以设置响应并获得使用groovy TestStep

中的follow groovy脚本请求testSteps的值
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);

此脚本获取您的json并使用第一个testStep响应中的值填充它,然后将此json设置为第二个testStep的请求。

希望这有帮助,

答案 1 :(得分:0)

你可能需要这样做:

​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()​

输出:

{
    "fieldToBeEncryptedList": [
        {
            "echoField": " ",
            "fieldName": " ",
            "srNo": "val2",
            "value": " "
        }
    ],
    "scopeId": "val1",
    "scopeType": " ",
    "userId": " "
}