0
0
Postmantesting~5 mins

Mock vs stub comparison in Postman

Choose your learning style9 modes available
Introduction

Mocks and stubs help test parts of software by pretending to be other parts. They make testing easier and faster.

When you want to test a feature but the real service is not ready or slow.
When you want to check how your code reacts to specific responses from another service.
When you want to isolate your test from external systems to avoid failures caused by them.
When you want to simulate error conditions that are hard to create with real services.
Syntax
Postman
Mock: A fake server or response that simulates real API behavior.
Stub: A simple fixed response used to replace a real API call.

Mocks can simulate complex behavior and multiple responses.

Stubs usually return fixed data and are simpler than mocks.

Examples
This mock simulates a GET request to '/user/1' and returns a user named Alice.
Postman
// Mock example in Postman
pm.mockServer.create({
  name: 'User API Mock',
  responses: [
    { request: { method: 'GET', url: '/user/1' }, response: { status: 200, body: '{"id":1,"name":"Alice"}' } }
  ]
});
This stub returns a fixed user response for the GET request to '/user/1'.
Postman
// Stub example in Postman test script
pm.stub('GET', '/user/1', {
  status: 200,
  body: '{"id":1,"name":"Stub User"}'
});
Sample Program

This test uses a stub to fake the weather API response. It checks that the status is 200 and temperature is 25.

Postman
// Postman test script using stub
pm.stub('GET', '/weather/today', {
  status: 200,
  body: '{"temp":25,"condition":"Sunny"}'
});

pm.sendRequest({
  url: 'https://api.example.com/weather/today',
  method: 'GET'
}, function (err, res) {
  pm.test('Status is 200', function () {
    pm.expect(res.status).to.eql(200);
  });
  pm.test('Response has temp 25', function () {
    const jsonData = res.json();
    pm.expect(jsonData.temp).to.eql(25);
  });
});
OutputSuccess
Important Notes

Mocks are more flexible and can simulate many scenarios.

Stubs are easier to create but less powerful.

Use mocks when you need to test complex interactions.

Summary

Mocks simulate real API behavior with flexible responses.

Stubs provide fixed responses to replace real calls.

Both help isolate tests and improve reliability.