Introduction
Mocks and stubs help test parts of software by pretending to be other parts. They make testing easier and faster.
Jump into concepts and practice - no test required
Mocks and stubs help test parts of software by pretending to be other parts. They make testing easier and faster.
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.
// 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"}' } } ] });
// Stub example in Postman test script pm.stub('GET', '/user/1', { status: 200, body: '{"id":1,"name":"Stub User"}' });
This test uses a stub to fake the weather API response. It checks that the status is 200 and temperature is 25.
// 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); }); });
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.
Mocks simulate real API behavior with flexible responses.
Stubs provide fixed responses to replace real calls.
Both help isolate tests and improve reliability.
mock and a stub in Postman testing?