Ready API, groovy script, how to pass a variable as an input of a field for Mongo DB document
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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"
}
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- then use double quotes around key value pairs
- "ID": "${#TestCase#SSN}"
Regards,
Rao.
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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
