0
0
Postmantesting~15 mins

Random data generation in Postman - Build an Automation Script

Choose your learning style9 modes available
Generate random user data in Postman pre-request script
Preconditions (3)
Step 1: Open the Postman app and select the request to automate
Step 2: Go to the Pre-request Script tab
Step 3: Write a script to generate a random first name, last name, and email
Step 4: Set these random values as environment variables
Step 5: Send the request using these variables in the request body or headers
Step 6: Verify the request payload contains the generated random data
✅ Expected Result: The request is sent with unique random user data each time, visible in the request body or headers, and environment variables hold the generated values.
Automation Requirements - Postman Sandbox JavaScript
Assertions Needed:
Verify environment variables for first name, last name, and email are set
Verify the request body or headers contain the generated random data
Best Practices:
Use Postman built-in random data functions like pm.variables.replaceIn or Math.random
Set environment variables using pm.environment.set
Keep scripts clean and readable
Avoid hardcoding values to ensure randomness
Automated Solution
Postman
pm.environment.set('firstName', `User${Math.floor(Math.random() * 1000)}`);
pm.environment.set('lastName', `Test${Math.floor(Math.random() * 1000)}`);
const email = `user${Math.floor(Math.random() * 1000)}@example.com`;
pm.environment.set('email', email);

console.log(`Generated user: ${pm.environment.get('firstName')} ${pm.environment.get('lastName')} <${pm.environment.get('email')}>`);

This script runs before the request is sent. It generates random numbers between 0 and 999 and appends them to fixed strings to create unique first names, last names, and emails.

We use pm.environment.set to save these values as environment variables. This way, the request can use {{firstName}}, {{lastName}}, and {{email}} placeholders in the body or headers.

The console.log helps to see the generated data in Postman's console for debugging.

Common Mistakes - 3 Pitfalls
Hardcoding random values instead of generating them dynamically
{'mistake': 'Setting variables in the wrong scope (e.g., local instead of environment)', 'why_bad': "Variables won't be accessible in the request if set in the wrong scope.", 'correct_approach': 'Use pm.environment.set to set environment variables accessible throughout the request.'}
Not using the generated variables in the request body or headers
Bonus Challenge

Now add data-driven testing by generating random user data for three different user roles: admin, editor, and viewer.

Show Hint