0
0
Postmantesting~15 mins

Collection variables in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify usage of collection variables in Postman requests
Preconditions (3)
Step 1: Open the 'User API Tests' collection
Step 2: Create a new GET request named 'Get User Info'
Step 3: Set the request URL to '{{baseUrl}}/users/123'
Step 4: Send the request
Step 5: Verify the response status code is 200
Step 6: Verify the response body contains a field 'id' with value 123
✅ Expected Result: The request uses the collection variable 'baseUrl' correctly, the response status code is 200, and the response body contains the user id 123
Automation Requirements - Postman/Newman
Assertions Needed:
Response status code is 200
Response body contains 'id' field with value 123
Best Practices:
Use pm.collectionVariables.get() to access collection variables
Use pm.test() for assertions
Avoid hardcoding URLs; use collection variables instead
Use descriptive test names
Automated Solution
Postman
pm.test('Status code is 200', function () {
    pm.response.to.have.status(200);
});

const userId = 123;
const responseJson = pm.response.json();
pm.test(`Response has user id ${userId}`, function () {
    pm.expect(responseJson.id).to.eql(userId);
});

The first test checks that the response status code is 200 using pm.response.to.have.status(200). This confirms the request was successful.

Next, we parse the response body as JSON with pm.response.json(). We then assert that the id field in the response equals the expected user id (123) using pm.expect().to.eql().

We use pm.test() to group assertions with descriptive names, making the test report clear.

The request URL uses the collection variable {{baseUrl}} to avoid hardcoding the API base URL, which improves maintainability.

Common Mistakes - 3 Pitfalls
Hardcoding the API URL instead of using collection variables
{'mistake': 'Not using pm.test() for assertions', 'why_bad': "Without pm.test(), assertions won't be reported properly in the test results.", 'correct_approach': 'Wrap assertions inside pm.test() with descriptive names for clear test reports.'}
{'mistake': 'Accessing variables incorrectly (e.g., using environment variables instead of collection variables)', 'why_bad': 'This can cause tests to fail if the wrong variable scope is used.', 'correct_approach': "Use pm.collectionVariables.get('variableName') to access collection variables explicitly."}
Bonus Challenge

Now add data-driven testing by running the same request for user IDs 101, 123, and 150 using collection variables

Show Hint