0
0
Postmantesting~15 mins

Environment file with Newman in Postman - Build an Automation Script

Choose your learning style9 modes available
Run Postman collection with environment file using Newman
Preconditions (3)
Step 1: Open terminal or command prompt
Step 2: Run Newman command to execute the collection with the environment file: newman run <collection-file.json> -e <environment-file.json>
Step 3: Observe the test run output in the terminal
✅ Expected Result: Newman runs the collection using the environment variables from the environment file and shows the test results in the terminal
Automation Requirements - Newman CLI
Assertions Needed:
Verify that Newman command runs without errors
Verify that environment variables are correctly loaded and used in the requests
Verify that test assertions in the collection pass
Best Practices:
Use explicit environment file with -e option
Check exit code of Newman command for success
Use descriptive names for environment variables
Keep environment files secure and do not commit sensitive data
Automated Solution
Postman
import subprocess

# Define paths to collection and environment files
collection_file = 'MyCollection.json'
environment_file = 'MyEnvironment.json'

# Run Newman command with environment file
result = subprocess.run([
    'newman', 'run', collection_file,
    '-e', environment_file
], capture_output=True, text=True)

# Print Newman output
print(result.stdout)

# Assert that Newman run was successful
assert result.returncode == 0, f"Newman run failed with exit code {result.returncode}"

This script uses Python's subprocess module to run the Newman CLI command that executes a Postman collection with a specified environment file.

The newman run command includes the -e option to specify the environment file, ensuring environment variables are loaded.

The script captures the output and prints it, so you can see the test run results in the console.

Finally, it asserts that the Newman command exited with code 0, which means the run was successful.

This approach automates running the collection with environment variables and verifies the execution result.

Common Mistakes - 4 Pitfalls
Not specifying the environment file with the -e option
Hardcoding sensitive data directly in the collection or script
{'mistake': 'Ignoring the exit code of the Newman command', 'why_bad': "You may miss test failures or errors if you don't check the exit code.", 'correct_approach': 'Check the return code after running Newman to confirm success or failure.'}
Using relative paths without confirming current working directory
Bonus Challenge

Now add data-driven testing by running the same collection with three different environment files

Show Hint