Ask a Question

Ready API, groovy script, how to pass a variable as an input of a field for Mongo DB document

Learningbear
Regular Visitor

Ready API, groovy script, how to pass a variable as an input of a field for Mongo DB document

I have a mongo DB collection with document structure as below

{

_id : ObjectId("5e66a38b478d946943329bba"),

name : "Tom",

age : 26, '

ID : "SD34re",

Gender : "Male"

}

I'm using groovy script in Ready API to make Mongo DB connection and fetch above document.

Now, I need to pass a dynamic value from variable "SSN" to ID value above. How can I do it using groovy script in Ready API.

Ex: def SSN = context.expand('${#TestCase#SSN}')

SSN value to be passed as below in document using groovy script in ReadyAPI. How can I achieve it?

{

_id : ObjectId("5e66a38b478d946943329bba"),

name : "Tom",

age : 26,

ID : SSN,

Gender : "Male"

}

2 REPLIES 2
nmrao
Community Hero

Re: Ready API, groovy script, how to pass a variable as an input of a field for Mongo DB document

If you are using the above document as json string,
- then use double quotes around key value pairs
- "ID": "${#TestCase#SSN}"


Regards,
Rao.
aaronpliu
Frequent Contributor

Re: Ready API, groovy script, how to pass a variable as an input of a field for Mongo DB document

Hi @Learningbear ,

Using groovy's GString to accept variable.

In ReadyAPI, you may get variable with context.expand('${#TestCase#SSN}') or testRunner.testCase.getPropertyByValue("SSN").

If you want to use variable in json or other data structure (like map, list), then you can use variable directly or using GString format (i.e. "$SSN" or "${SSN}").

JSON / LinkedHashMap / ArrayList object would be serialization to json data with groovy.json.JsonSlurper

import groovy.json.JsonOutput

def SSN = context.expand('${#TestCase#SSN}')
def data = ["_id": "ObjectId(5e66a38b478d946943329bba)","name": "Tom", "age": 26, "ID": SSN, "Gender": "Male"
]

log.info JsonOutput.prettyPrint(JsonOutput.toJson(data))

// output

{

_id : ObjectId("5e66a38b478d946943329bba"),

name : "Tom",

age : 26, '

ID : "SD34re",

Gender : "Male"

}

 

 

Thanks,

/Aaron

cancel
Showing results for 
Search instead for 
Did you mean: