0
0
Postmantesting~15 mins

Mock vs stub comparison in Postman - Automation Approaches Compared

Choose your learning style9 modes available
Compare behavior of mock server and stub in Postman
Preconditions (2)
Step 1: Create a stub response for GET /user/profile with fixed JSON data
Step 2: Send a request to the stub and verify the response matches the stub data
Step 3: Create a mock server in Postman with the same GET /user/profile endpoint and response
Step 4: Send a request to the mock server and verify the response matches the mock data
Step 5: Change the mock server response data and send the request again to verify dynamic response
Step 6: Attempt to change the stub response and observe that it requires manual update
✅ Expected Result: Stub returns fixed response that does not change unless manually updated. Mock server can return dynamic responses and simulate different scenarios without changing the actual API.
Automation Requirements - Postman test scripts
Assertions Needed:
Response body matches expected stub JSON
Response body matches expected mock JSON
Response status code is 200
Response changes when mock server response is updated
Best Practices:
Use pm.test and pm.expect for assertions
Use environment variables for URLs
Keep test scripts simple and readable
Use descriptive test names
Automated Solution
Postman
pm.test('Status code is 200', () => {
    pm.response.to.have.status(200);
});

const expectedStubResponse = {
    "id": 1,
    "name": "John Doe",
    "email": "john@example.com"
};

pm.test('Response matches stub data', () => {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.eql(expectedStubResponse);
});

// For mock server test, update expectedMockResponse accordingly
const expectedMockResponse = {
    "id": 1,
    "name": "John Doe",
    "email": "john@example.com"
};

pm.test('Response matches mock data', () => {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.eql(expectedMockResponse);
});

This Postman test script checks that the response status code is 200, which means the request was successful.

It then compares the JSON response body to the expected stub data using pm.expect().to.eql() to ensure the stub returns the fixed data.

Similarly, it compares the response to the expected mock data to verify the mock server returns the correct response.

Using environment variables for URLs allows easy switching between stub and mock endpoints.

Each test has a clear name to explain what it verifies.

Common Mistakes - 3 Pitfalls
Not verifying the response status code before checking the body
Hardcoding URLs in test scripts
Using loose equality checks instead of deep equality for JSON
Bonus Challenge

Now add data-driven testing by running the same tests with 3 different user profiles in stub and mock responses

Show Hint