SOAP UI - Return two different responses for two different POST Request Payloads for same REST API end point

扶醉桌前 提交于 2021-02-11 14:09:36

问题


I have a REST POST API end point - "abc/def".
It's request payload has (out of many other fields) a field "yourId" which can take either 1 or 2 as shown below:

{
  "yourId":"1"
}

OR

{
  "yourId":"2
}

On the basis of the value of "yourId", I need to return two different responses either 1. YOUR_RESPONSE_1 OR 2. YOUR_RESPONSE_2 for which I have written a groovy script as shown below:

def requestBody = mockRequest.getRequestContent()
log.info "Request body: " + requestBody
yourId="yourId"
id1="1"
id2="2"
if(requestBody.contains(yourId+":"+id1)){
    return "YOUR_RESPONSE_1"
}else if(requestBody.contains(yourId+":"+id2)){
    return "YOUR_RESPONSE_2"
}else return "ERROR_RESPONSE" 

When I hit the end point "localhost:8080/abc/def" from postman, I get ERROR_RESPONSE. How can I fix it.


回答1:


I would suggest you to use the JSONSlurper() as this avoids the use of escape characters and makes the script legible, Also it come in handy when the input JSON is complex

def requestBody = mockRequest.getRequestContent()
def parsedJson = new groovy.json.JsonSlurper().parseText(requestBody)
def ID =  parsedJson.yourId

if(ID=="1"){
    return "YOUR_RESPONSE_1"
}
else if(ID=="2"){
    return "YOUR_RESPONSE_2"
}
else return "ERROR_RESPONSE" 


来源:https://stackoverflow.com/questions/62465542/soap-ui-return-two-different-responses-for-two-different-post-request-payloads

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!