0
0
Postmantesting~15 mins

Defining mock responses in Postman - Build an Automation Script

Choose your learning style9 modes available
Create and verify a mock response for a GET user API
Preconditions (2)
Step 1: Open the Postman app and select the collection containing GET /user
Step 2: Click on the 'Mocks' tab in the collection view
Step 3: Click 'Create a mock server'
Step 4: Set the mock server name to 'User API Mock'
Step 5: Select the GET /user request to mock
Step 6: Define the mock response with status 200 and JSON body: {"id":1,"name":"John Doe"}
Step 7: Save the mock server
Step 8: Send a GET request to the mock server URL for /user
Step 9: Verify the response status is 200
Step 10: Verify the response body matches {"id":1,"name":"John Doe"}
✅ Expected Result: The mock server returns the defined JSON response with status 200 when GET /user is called
Automation Requirements - Postman test scripts
Assertions Needed:
Response status code is 200
Response body JSON matches the mock data
Best Practices:
Use Postman built-in pm.test and pm.response APIs for assertions
Keep mock response JSON simple and clear
Use environment variables for mock server URL
Validate both status code and response body
Automated Solution
Postman
pm.test('Status code is 200', () => {
    pm.response.to.have.status(200);
});

pm.test('Response body matches mock data', () => {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.eql({ id: 1, name: 'John Doe' });
});

The first test checks that the response status code is exactly 200, which means success.

The second test parses the response body as JSON and compares it to the expected mock object with id 1 and name 'John Doe'.

Using pm.test groups assertions with clear names, making test reports easy to understand.

This script runs automatically after sending the request to the mock server, verifying the mock response is correct.

Common Mistakes - 3 Pitfalls
Not verifying the response status code
Comparing response body as a string instead of JSON object
Hardcoding mock server URL in tests
Bonus Challenge

Now add data-driven testing by defining three different mock responses for GET /user with different user data and verify each response.

Show Hint