Needing help with how to format List variable types within Web Service Requests request bodies

For my scenario we have an array variable in our PUT request type. It is just a list of strings. So, it is simple enough for me to just use the Web Service Request variables. Then I can just slot in what I need when I create the tests. I need help with how to format the variable name within the Web Service Request object request body. Here is what the request would look like hard coded.

{
  "listOfTestItems": [
    "test3", 
    "test2",
    "test1"
  ]
}

Below is what I have tried.

{
  "listOfTestItems": [
    "${itemList}"
  ]
}
{
  "listOfTestItems": 
    "${itemList}"
}

Here is how I setup the variable.
image

the problem here is, your variable is a list, using it like that in the body will result in unquoted values.
so you have to convert it into json format before to use it in the body.

following code may help:

def list = ["one", "two", "three"]  //use your list variable instead

//convert list to quoted strings
String strList = new groovy.json.JsonBuilder(list).toString()
println strList


// build the final body
body = """
{
  "listOfTestItems": ${strList}
}
"""

println body

result:

["one","two","three"]


{
  "listOfTestItems": ["one","two","three"]
}

you can do it also in one line:

def itemList = ["one", "two", "three"] //not needed, use your variable

// if you do this in the request builder simply use what is between the quotes
body = """
{
  "listOfTestItems": ${new groovy.json.JsonBuilder(itemList).toString()}
}
"""

println body

will produce the same result as above

option two: use inspect + replace all (inspect will produce single quoted strings)

body = """
{
  "listOfTestItems": ${itemList.inspect().replaceAll("\'","\"")}
}
"""

result:

{
  "listOfTestItems": ["one", "two", "three"]
}

Is there a way to do this within one of the Web Service Request keywords? Or do we need to just create a new custom keyword for these types of requests?

the ‘one line’ form may work from the web request, in the end is just a closure (but i am not sure, never tried like this)
try to set your body like this:

{
"listOfTestItems": ${itemList.inspect().replaceAll("\'","\"")}
}

(or use the JsonBuilder variant)

If it is not working as expected, you have two options:

  • define a ‘body’ empty string variable in the web request and just put ${body} in the body section of the request
  • build the ‘body’ variable in the testcase using one of the above examples (the itemList can be a global variable or a testcase variable)
  • call the web request from the testcase passing the body variable to it

or use a custom keyword