0
0
Postmantesting~15 mins

Environment switching in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify API response changes when switching Postman environments
Preconditions (4)
Step 1: Select the 'Development' environment in Postman
Step 2: Send the GET request to {{baseUrl}}/status
Step 3: Note the response status code and body
Step 4: Switch to the 'Production' environment
Step 5: Send the same GET request again
Step 6: Note the response status code and body
✅ Expected Result: The response status code and body should differ between 'Development' and 'Production' environments, reflecting the different baseUrl values.
Automation Requirements - Postman/Newman
Assertions Needed:
Verify response status code is 200 for both environments
Verify response body contains expected environment-specific data
Verify that the baseUrl variable is correctly used in the request URL
Best Practices:
Use environment variables for base URLs
Use pm.environment.set and pm.environment.get to manage variables
Use pm.test for assertions
Run tests separately for each environment
Avoid hardcoding URLs in requests
Automated Solution
Postman
pm.test('Status code is 200', function () {
    pm.response.to.have.status(200);
});

pm.test('Response body contains environment info', function () {
    const responseJson = pm.response.json();
    const env = pm.environment.name;
    pm.expect(responseJson.environment).to.eql(env);
});

The first test checks that the response status code is 200, which means the request was successful.

The second test parses the JSON response and verifies that the 'environment' field matches the current environment name. This confirms that the request used the correct baseUrl from the environment.

These tests should be run separately with the 'Development' and 'Production' environments selected in Postman to verify environment switching.

Common Mistakes - 3 Pitfalls
Hardcoding the API URL instead of using environment variables
Not selecting the correct environment before running the test
Not using pm.test assertions to verify response data
Bonus Challenge

Now add data-driven testing by running the same test with three different environments: Development, Staging, and Production.

Show Hint