Oct 12, 2020

API Testing 'A Beginners View': Dynamic Variable Usage

Postman uses the pseudo library to generate dummy data. You can generate random names, addresses, email addresses, and much more. You can use these pre-defined variables multiple times to return different values per request. Also, you can use these variables like any other variable defined in Postman. Their values are generated at the time of execution and their names start with a $ symbol e.g. $randomPhoneNumber, $randomCity, $randomDateFuture, etc.

To use dynamic variables in pre-request or test scripts, you need to use:
  • pm.variables.replaceIn()
  • e.g. pm.variables.replaceIn('{{$randomFirstName}}').
Recently in my daily routine work, got to use this feature, so here is how I made use of the dynamic variables 😇

My Requirement: Fetch $randomeFirstName and set the real value of $randomFirstName at the environmental level so I can access it in the test script.

Solution: 

1. In Pre-Request Script: 
    • Define a function to return the randomly generated value
    • Set an environment variable to hold the randomly generated value that returns from the function defined.
    • Snippet: 
    pm.environment.set("RandomFirstName"getRandomFirstName());
    function getRandomFirstName() {
        const RandomFirstName = pm.variables.replaceIn("{{$randomFirstName}}");
        return RandomFirstName;
    }
2. In Body: Call the variable defined at that environment level
{
"FirstName": [{
            "value": "{{RandomFirstName}}"
        }]
}

3. Example:





No comments: