Implementing Mock and Stub Responses
1. Configuring Static Mock Responses
Example: Static JSON mock
routes:
- paths: ["/mock/users/42"]
plugins:
- name: request-termination
config:
status_code: 200
content_type: application/json
body: '{"id":42,"name":"Test User","email":"test@example.com"}'
2. Using Dynamic Mock Data Generation
| Source | Tool |
|---|---|
| Faker | faker.js, faker.py |
| Schema-driven | json-schema-faker |
| OpenAPI examples | Prism mock server |
| Seeded | Deterministic by request hash |
3. Using Mock Response Templates
Example: Templated mock
{
"id": "{{ request.path.id }}",
"name": "{{ faker.name }}",
"email": "{{ faker.email }}",
"created_at": "{{ now }}",
"request_id": "{{ request.headers.x-request-id }}"
}
4. Implementing Response Delays
| Purpose | Delay |
|---|---|
| Simulate slow backend | 500ms-5s fixed |
| Realistic latency | Random in p50-p99 range |
| Timeout test | > client timeout |
| Loading state UI | 200-1000ms |
5. Setting Up Conditional Mocking
Example: Conditional by header
local scenario = kong.request.get_header("x-mock-scenario")
if scenario == "404" then
return kong.response.exit(404, { error = "not_found" })
elseif scenario == "slow" then
ngx.sleep(3)
elseif scenario == "rate_limit" then
return kong.response.exit(429, { error = "too_many" })
end
6. Configuring Mock Response Headers
| Header | Mock Value |
|---|---|
X-Mock-Source | prism / wiremock / static |
X-Mock-Scenario | Scenario ID |
X-Request-Id | Echo for correlation |
Cache-Control | no-store (avoid cached mocks) |
7. Implementing Random Response Selection
| Strategy | Use |
|---|---|
| Random pick from list | Realistic variation |
| Weighted (90/10) | Mostly success, sometimes error |
| Round robin | Predictable cycle |
| Hash by input | Same request → same response |
8. Setting Up Mock Error Scenarios
| Scenario | Trigger |
|---|---|
| 400 Bad Request | Specific body field |
| 401 Unauthorized | Missing/invalid token |
| 409 Conflict | Duplicate ID |
| 500 Server Error | Magic value ?fail=500 |
| Timeout | Specific path |
9. Configuring Mock Data Persistence
| Storage | Use |
|---|---|
| In-memory | Reset per request |
| Per-session | Cookie-keyed, ephemeral |
| Per-user | Auth-tied |
| Shared SQLite | Cross-session, low-volume |
10. Using External Mock Services
| Service | Best For |
|---|---|
| Prism | OpenAPI spec-driven |
| WireMock | Recording, stubbing |
| Mockoon | GUI, local-first |
| Beeceptor | Hosted, share via URL |
| MockServer | Java-based, expectations |