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

SourceTool
Fakerfaker.js, faker.py
Schema-drivenjson-schema-faker
OpenAPI examplesPrism mock server
SeededDeterministic 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

PurposeDelay
Simulate slow backend500ms-5s fixed
Realistic latencyRandom in p50-p99 range
Timeout test> client timeout
Loading state UI200-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

HeaderMock Value
X-Mock-Sourceprism / wiremock / static
X-Mock-ScenarioScenario ID
X-Request-IdEcho for correlation
Cache-Controlno-store (avoid cached mocks)

7. Implementing Random Response Selection

StrategyUse
Random pick from listRealistic variation
Weighted (90/10)Mostly success, sometimes error
Round robinPredictable cycle
Hash by inputSame request → same response

8. Setting Up Mock Error Scenarios

ScenarioTrigger
400 Bad RequestSpecific body field
401 UnauthorizedMissing/invalid token
409 ConflictDuplicate ID
500 Server ErrorMagic value ?fail=500
TimeoutSpecific path

9. Configuring Mock Data Persistence

StorageUse
In-memoryReset per request
Per-sessionCookie-keyed, ephemeral
Per-userAuth-tied
Shared SQLiteCross-session, low-volume

10. Using External Mock Services

ServiceBest For
PrismOpenAPI spec-driven
WireMockRecording, stubbing
MockoonGUI, local-first
BeeceptorHosted, share via URL
MockServerJava-based, expectations