Forum Discussion

martinh3345's avatar
martinh3345
New Contributor
5 years ago

SoapUI - How to create dynamic array mock responses for REST call

I currently have a REST mock service setup for a POST call that responds with different responses depending on the content of the call, this is all working fine but I need this to be able to handle a...
  • martinh3345's avatar
    5 years ago

    Thanks

     

    I managed to get this working in the end. I picked up the incoming requests and set them as an array, managed to loop through them and build up a variable containing dynamic responses to each and output the variable as my response. 

     

    Here's my code for anyone interested, not the prettiest but did the job

     

    // Parse the JSON request.
    def jsonrequest = new groovy.json.JsonSlurper().parseText(mockRequest.getRequestContent())

     

    // Capture values from request
    requestContext.echoOrderCorrelationId = jsonrequest.orderCorrelationId

     

    //Define Incoming Array for CorrelationIds 
    def myarray = new ArrayList<String>(requestContext.echoOrderCorrelationId)
    def arraysize = myarray.size()

     

    //set variables for use in while loop
    def count = 0
    String Response = '['
    String Full = ''

    while(count < arraysize)
    {
    //take the correlation ID for item in the loop
    def CorrelationID = myarray.get(count)
    //write the body of the response for the item in the loop
    String Body = '{"orderCorrelationId": "' + CorrelationID + '","customerName": "MOCK Customer","responseStatuses": [{"code": "","message": "OK","severity": "INFO"}]}'

     

    //increment the count
    count++

    //check if last iteration
    if (count < arraysize)
    {
    //add comma to continue adding records
    Full = Response + Body + ','
    Response = Full
    }
    else
    {
    //add ] to finalise response
    Full = Response + Body + ']'
    Response = Full
    }
    log.info "Body = ${Response}"
    }

    //set variable to return for Response Body
    requestContext.ResponseBody = Response

     

    For my response I just default to an OK and use ${ResponseBody} to output my variable