API mocking is a technique used to simulate the behavior of real APIs during testing. It helps isolate your system under test, test edge cases, and avoid dependencies on external services.
Tools for API Mocking
Choose a tool based on your tech stack:
- Java: WireMock, MockServer
- JavaScript: MSW (Mock Service Worker), Nock
- Python: responses, httpretty
- Postman: Postman Mock Server
- Standalone: Beeceptor, Mocky
Setup Steps
1. Define Mock Endpoints
Specify
- URL (e.g., /api/users)
- HTTP method (GET, POST, etc.)
- Response body (JSON/XML)
- Status code (200, 404, etc.)
- Headers (optional)
Example (WireMock JSON config)
{
"request": {
"method": "GET",
"url": "/api/users/123"
},
"response": {
"status": 200,
"body": "{\"id\":123,\"name\":\"Pratik\"}",
"headers": {
"Content-Type": "application/json"
}
}
}
2. Integrate with Your Test Framework
JavaScript (MSW Example)
import { setupServer } from 'msw/node';
import { rest } from 'msw';
const server = setupServer(
rest.get('/api/users/:id', (req, res, ctx) => {
return res(ctx.status(200), ctx.json({ id: req.params.id, name: 'Pratik' }));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Python (responses Example)
import responses
import requests
@responses.activate
def test_api_mock():
responses.add(
responses.GET,
'http://example.com/api/users/123',
json={'id': 123, 'name': 'Pratik'},
status=200
)
resp = requests.get('http://example.com/api/users/123')
assert resp.json() == {'id': 123, 'name': 'Pratik'}
Best Practices
- Version control your mocks: Store mock definitions in Git.
- Use environment flags: Switch between real and mock APIs.
- Simulate failures: Test timeouts, 500 errors, and invalid responses.
- Keep mocks realistic: Use tools like Faker for dynamic data.
- Automate mock server startup: Integrate with CI/CD pipelines.