Inferensys

Prompt

API Mock and Stub Generation for UI Test Prompt Template

A practical prompt playbook for using API Mock and Stub Generation for UI Test Prompt Template in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job-to-be-done, the ideal user, and the constraints for generating API mocks and stubs for UI testing.

This prompt is for SDETs and automation engineers who need to decouple UI tests from live, flaky, or incomplete backend services. The core job-to-be-done is generating a functional mock server definition—complete with request matching, response templating, and stateful scenario sequences—that allows a UI test suite to run deterministically in CI/CD. The ideal user has a clear OpenAPI spec, a set of recorded API interactions, or a list of specific endpoints they need to stub. They are not looking for a generic 'how to mock' guide; they need a concrete, runnable stub configuration that handles the specific data shapes, error states, and sequencing their UI tests require.

You should use this prompt when the cost of live backend dependencies—slow test execution, environment contention, flaky network calls, or the inability to simulate error and edge cases—outweighs the value of end-to-end integration. It is particularly effective for generating stubs that simulate race conditions, slow responses, and specific error codes (e.g., 429, 503) that are hard to trigger on demand. The prompt expects structured inputs like an OpenAPI schema, a list of endpoints, or a HAR file. Without these, the generated mocks will be generic and require significant rework. Do not use this prompt to generate mock data for performance or load testing; those scenarios require a different scale of data generation and response timing.

A critical constraint is mock-to-real drift. The generated stubs are only as good as the contract they are built from. If the real API changes, the mocks become a source of false positives. The implementation harness must therefore include a contract drift detection step. Additionally, avoid over-mocking: if a UI test's primary purpose is to verify a complex backend integration, replacing that backend with a simple stub invalidates the test. Use this prompt for UI behavior tests, not for backend integration tests. Before generating stubs, confirm that the test's value is in the client-side logic, rendering, and user interaction, not in the backend's business logic.

After generating the stub configuration, your next step is to wire it into a mock server like WireMock, Mockoon, or a Playwright route interceptor. The prompt's output should be directly translatable into that server's configuration format. You must then validate the stubs by running the UI tests against them and checking for contract drift against the live API's specification. If the prompt generates a stateful scenario (e.g., 'first call returns empty, second returns data'), ensure your test harness can reset that state between test cases to prevent cross-test contamination.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if API mock generation is the right tool for your UI test scenario.

01

Good Fit: Isolated UI Workflows

Use when: UI tests need deterministic backend responses for happy path, loading, empty, and error states. Guardrail: Define the mock contract before generating stubs. Use OpenAPI specs or recorded traffic as the source of truth to prevent mock drift.

02

Bad Fit: End-to-End Integration Testing

Avoid when: The test goal is to verify real backend behavior, database state, or third-party service contracts. Guardrail: Reserve mocks for UI-layer validation. For integration tests, use ephemeral environments or service virtualization instead of static stubs.

03

Required Input: API Contract or Traffic Sample

Risk: Generating mocks without a contract produces stubs that match nothing real. Guardrail: Always provide an OpenAPI spec, HAR file, or typed request/response examples. The prompt should refuse to generate mocks when no contract is supplied.

04

Operational Risk: Mock Rot

Risk: Mocks become stale as the real API evolves, causing false-positive UI test passes. Guardrail: Schedule contract drift detection by comparing mock response shapes against the latest API spec weekly. Fail the mock build if schemas diverge.

05

Operational Risk: Over-Mocking Complexity

Risk: Stateful scenario sequences with multiple steps become harder to maintain than the tests they support. Guardrail: Limit mock state machines to three transitions. If a test requires complex orchestration, reconsider whether the UI test is the right layer.

06

Required Input: Error Simulation Coverage

Risk: Mocks that only return 200 OK leave error handling untested. Guardrail: Require explicit error scenarios in the prompt input: 4xx, 5xx, network timeouts, and malformed payloads. Validate that each generated stub includes at least one failure mode.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating API mock server definitions that enable UI tests to run without live backends.

This prompt template produces structured mock API definitions—including request matching rules, response templates, and stateful scenario sequences—from a combination of an API specification, UI test requirements, and the specific test scenarios that need controlled backend behavior. Copy the template below, replace the square-bracket placeholders with your actual inputs, and run it through your model. The output should be a ready-to-use mock server configuration or stub file that your test harness can consume directly.

text
You are an SDET specialized in API mocking for UI test automation. Your task is to generate a complete mock server definition that enables UI tests to run without a live backend.

## INPUTS

### API Specification
[API_SPEC]

### UI Test Requirements
[TEST_REQUIREMENTS]

### Test Scenarios to Support
[TEST_SCENARIOS]

### Mock Framework
[FRAMEWORK: WireMock | Mock Service Worker | Playwright Route Interception | Cypress Intercept | json-server | Other]

### Output Format
[OUTPUT_FORMAT: JSON stub mappings | TypeScript handlers | YAML configuration | Other]

## CONSTRAINTS

- Generate request matching rules that are specific enough to avoid cross-test interference but flexible enough to handle dynamic path parameters, query strings, and request bodies.
- Include response templating for fields that must vary per request (timestamps, IDs, pagination tokens).
- For stateful scenarios, define sequences where the same endpoint returns different responses based on invocation count or prior state transitions.
- Cover at minimum: success responses, validation error responses (400/422), authentication error responses (401/403), not-found responses (404), and server error responses (500/503).
- Include configurable response delays to simulate network latency.
- Add comments explaining which test scenario each stub supports and any assumptions about request state.
- If the mock framework supports it, include response header configuration (Content-Type, CORS, caching directives).
- Flag any mock behavior that could mask real application bugs (e.g., always returning 200 when the real API would return an error under certain conditions).

## OUTPUT STRUCTURE

For each mock endpoint, provide:
1. **Request matcher**: HTTP method, URL pattern, headers, query parameters, body matchers
2. **Response definition**: Status code, headers, body template, fixed delay or distribution
3. **Scenario metadata**: Which test scenario(s) this stub supports, state dependencies, invocation count constraints
4. **Drift risk note**: What could change in the real API that would make this mock invalid

## ADDITIONAL INSTRUCTIONS

- If the API specification includes schema definitions, use them to generate response bodies that match the expected shape exactly.
- If the test scenarios require specific data values (e.g., a user with a known ID, an order in a specific state), hardcode those values in the response templates.
- For error scenarios, ensure the error response body matches the real API's error envelope structure.
- If [RISK_LEVEL] is "high" (e.g., financial transactions, healthcare data, authentication), add a note requiring human review before the mocks are committed to the test suite.
- Do not generate mocks for endpoints or scenarios not listed in [TEST_SCENARIOS].

Adaptation guidance: Replace [API_SPEC] with your OpenAPI document, GraphQL schema, or a plain-text description of the endpoints. [TEST_REQUIREMENTS] should describe what the UI test needs to verify—this constrains which response shapes matter. [TEST_SCENARIOS] is the critical input: list each test case with its expected API interactions, including error states and edge cases. Set [RISK_LEVEL] to "high" for regulated domains, which activates the human-review requirement in the output. After generation, validate that every mock endpoint maps to at least one test scenario and that error simulation coverage matches your test plan. If the output includes mocks for endpoints not referenced in your scenarios, remove them—they add maintenance cost without test value.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the API Mock and Stub Generation prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check the input quality before generation.

PlaceholderPurposeExampleValidation Notes

[API_SPECIFICATION]

The OpenAPI, GraphQL schema, or endpoint contract that defines request/response shapes, status codes, and error bodies.

openapi: 3.0.0 paths: /users/{id}: get: responses: '200': content: application/json: schema: $ref: '#/components/schemas/User'

Schema parse check: must be valid OpenAPI 3.x, GraphQL SDL, or gRPC proto. Reject if schema is empty, unparseable, or missing response definitions for the target endpoint.

[TARGET_ENDPOINTS]

The specific API paths or operations that need mock stubs. Prevents generating mocks for the entire API surface when only a subset is needed for UI tests.

["GET /users/{id}", "POST /users", "GET /users/{id}/orders"]

Must be a non-empty array of valid paths present in [API_SPECIFICATION]. Reject if any path does not exist in the spec or if the array is empty.

[MOCK_SERVER_FRAMEWORK]

The mock server library or tool that will serve the stubs. Determines the output format for stub definitions.

"wiremock"

Must be one of: wiremock, mountebank, msw, json-server, prism, mockoon, or custom. Reject if unrecognized or unsupported. Default to msw if not specified.

[UI_TEST_SCENARIOS]

The specific UI test cases that will consume these mocks. Provides context for which response variants, error states, and edge cases the mocks must support.

["View user profile with valid ID", "View user profile with expired session (401)", "View user profile when user not found (404)", "View user profile during server error (500)"]

Must be a non-empty array of scenario descriptions. Each scenario should imply a response state. Warn if scenarios only cover happy-path and no error states are included.

[RESPONSE_DELAY_MS]

Simulated network latency in milliseconds for each stub response. Enables UI tests to verify loading states, spinners, and timeout handling.

200

Must be an integer between 0 and 30000. Reject if negative or non-numeric. Warn if set to 0 when UI tests include loading-state assertions. Default to 200 if not provided.

[STATEFUL_SCENARIOS]

Multi-step scenario sequences where mock responses must change based on prior request state. Optional. Use null when only stateless stubs are needed.

[{"name": "Create then fetch user", "steps": ["POST /users returns 201 with new ID", "GET /users/{id} returns created user"]}]

Null allowed. If provided, each scenario must have a name and a non-empty steps array. Each step must reference a valid endpoint from [TARGET_ENDPOINTS]. Reject if steps reference endpoints not in scope.

[CONTRACT_DRIFT_CHECK]

Whether to generate a contract drift detection harness that compares mock response shapes against the current API specification. Optional boolean.

Must be true or false. Default to true. When true, the prompt must include instructions for generating a schema validator that runs before tests and flags mismatches between mock response bodies and the spec.

[OUTPUT_FORMAT]

The file format and structure for the generated stub definitions and harness code.

"json"

Must be one of: json, yaml, typescript, javascript. Reject if unrecognized. Default to json for wiremock/mountebank, typescript for msw. Must align with [MOCK_SERVER_FRAMEWORK] conventions.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the API mock generation prompt into a test harness with validation, drift detection, and safe execution.

The API mock and stub generation prompt is designed to be called programmatically as part of a UI test authoring pipeline, not as a one-off chat interaction. The typical integration point is a CLI tool, a CI job, or an internal developer portal where an SDET provides an OpenAPI spec, a set of test scenarios, and a target mock framework (e.g., Mock Service Worker, WireMock, or Playwright route handlers). The application layer is responsible for assembling the prompt with the correct [OPENAPI_SPEC], [TEST_SCENARIOS], and [MOCK_FRAMEWORK] placeholders, then parsing the structured output into files that can be committed alongside the UI tests.

Before writing the generated stubs to disk, the harness must run a validation pass. The prompt template requests a specific [OUTPUT_SCHEMA]—typically a JSON array of stub definitions with fields for request matching, response templating, and scenario sequencing. Your harness should validate that every stub has a unique match rule, that response templates reference only fields present in the OpenAPI spec, and that stateful scenario sequences (e.g., 'first call returns 200, second call returns 429') are explicitly ordered. Reject any output that contains unresolved template variables, references to endpoints not in the provided spec, or mock logic that branches on headers the real API never sends. For high-risk test suites where a bad mock could mask a production defect, route the generated stubs to a human reviewer before they land in the shared test repository.

The most common production failure mode is contract drift: the generated mocks pass tests but no longer match the real API's behavior. To catch this, schedule a weekly drift-detection job that diffs the current OpenAPI spec against the spec version used when the mocks were generated. Flag any endpoint whose response schema, status codes, or required headers have changed. A second drift check should replay a sample of recent real API traffic against the mock definitions and log any request that would not match a stub—these represent untested API interactions. When drift is detected, re-run the prompt with the updated spec and the original test scenarios, then diff the new stubs against the existing ones to generate a reviewable change list. Do not auto-apply mock updates without human review if the test suite gates a release.

For model choice, prefer a model with strong JSON schema adherence and long-context handling, since OpenAPI specs can be large. If the spec exceeds the model's context window, preprocess it by extracting only the endpoints, schemas, and examples referenced by the provided test scenarios. Log every prompt invocation with the spec version, scenario list, and generated stub hash so you can trace which prompt run produced which mock file. If a generated stub causes a test to pass when it should fail, the trace lets you identify the exact prompt input that created the faulty mock and iterate on the template's [CONSTRAINTS] section to prevent recurrence.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required structure, types, and validation rules for the mock API stub definition generated by the prompt. Use this contract to validate the output before wiring it into a mock server or UI test harness.

Field or ElementType or FormatRequiredValidation Rule

mock_server_config

object

Must contain a top-level key for the mock server framework (e.g., mockserver, wiremock, msw). Schema check: object with exactly one recognized framework key.

framework_key

string

Must match one of the supported frameworks: mockserver, wiremock, msw, or mountebank. Enum check: value in allowed set.

stubs

array

Must be a non-empty array of stub definition objects. Schema check: array length > 0.

stubs[].id

string

Unique identifier for the stub. Must be a kebab-case string. Format check: matches regex ^[a-z0-9]+(-[a-z0-9]+)*$.

stubs[].request.method

string

HTTP method for request matching. Must be one of GET, POST, PUT, PATCH, DELETE. Enum check: value in allowed set.

stubs[].request.url_pattern

string

URL pattern for request matching. Must be a valid path pattern (e.g., /api/users/{id}). Format check: starts with / and contains no spaces.

stubs[].response.status

integer

HTTP status code for the mock response. Must be a valid HTTP status code. Range check: 100-599.

stubs[].response.body

object or array

Response body payload. Must be valid JSON-serializable structure. Parse check: JSON.parse succeeds without error.

stubs[].response.headers

object

Response headers as key-value pairs. If present, all keys must be strings and values must be strings. Schema check: typeof key === string and typeof value === string.

stubs[].response.delay_ms

integer

Simulated response delay in milliseconds. If present, must be a non-negative integer. Range check: value >= 0.

stubs[].scenario

object

Stateful scenario configuration for sequenced responses. If present, must contain scenario_name (string) and required_state (string). Schema check: required keys present.

stubs[].scenario.scenario_name

string

true if scenario present

Name of the stateful scenario. Must be a snake_case string. Format check: matches regex ^[a-z]+(_[a-z]+)*$.

stubs[].scenario.required_state

string

true if scenario present

State that must be active for this stub to match. Must be a snake_case string. Format check: matches regex ^[a-z]+(_[a-z]+)*$.

stubs[].scenario.new_state

string

true if scenario present

State to transition to after this stub is matched. Must be a snake_case string. Format check: matches regex ^[a-z]+(_[a-z]+)*$.

error_simulation_stubs

array

Stubs for error scenarios (4xx, 5xx, timeouts). If present, must contain at least one stub with response.status >= 400. Schema check: array contains error status stub.

contract_drift_notes

array of strings

Warnings about potential drift between mock and real API contract. Each entry must be a non-empty string describing a specific drift risk. Content check: string length > 0.

PRACTICAL GUARDRAILS

Common Failure Modes

API mock generation fails in predictable ways. These are the most common failure modes when generating stubs for UI tests, along with practical guardrails to catch them before they corrupt your test suite.

01

Mock-to-Real Contract Drift

What to watch: The generated stub matches today's API contract but silently diverges when the real backend changes a field name, adds a required property, or alters a status code. UI tests pass against the stale mock while production breaks. Guardrail: Generate a contract verification step that diffs the mock's response schema against the latest OpenAPI spec or a recorded real response. Fail the mock generation if schema drift exceeds a threshold.

02

Missing Error-State Simulation

What to watch: The prompt produces only happy-path stubs (200 with valid bodies). The UI test suite never exercises loading states, network failures, 4xx errors, 5xx errors, or timeout conditions. Error-handling UI code goes untested. Guardrail: Require the prompt to generate at least one stub per error category listed in the API spec. Add a harness check that counts error-status stubs and flags any mock set with zero error scenarios.

03

Stateful Scenario Sequence Gaps

What to watch: The prompt generates individual stubs but fails to model state transitions—e.g., POST creates a resource, but the subsequent GET stub doesn't reflect the created state. Multi-step UI flows break because mock state doesn't match expected causality. Guardrail: Validate that generated scenario sequences include at least one write-then-read pair with consistent state. Use a state-machine checker that replays the sequence and verifies response coherence.

04

Over-Engineering Mocks Beyond Test Value

What to watch: The prompt generates a fully dynamic mock server with request matching, response templating, latency simulation, and conditional branching—for a test that only needs a single static 200. Mock complexity exceeds the test's coverage value, increasing maintenance burden. Guardrail: Add a complexity budget to the prompt: specify the maximum number of stubs, response variants, and state transitions per test. Run a post-generation complexity check that warns when the mock set exceeds the budget.

05

Hardcoded Identifiers and Non-Idempotent Stubs

What to watch: Generated stubs embed fixed resource IDs, timestamps, or sequence-dependent values that collide across test runs. Tests pass once and fail on rerun because the mock returns the same ID that already exists in the test's state. Guardrail: Require the prompt to use templated identifiers (e.g., {{uuid}}, {{timestamp}}) or request-matching wildcards. Add a harness check that detects hardcoded UUIDs, incrementing integers, or ISO timestamps in stub response bodies.

06

Incomplete Request Matching Rules

What to watch: The prompt generates stubs that match only on URL path, ignoring query parameters, headers, or request body shape. A UI test that sends GET /users?role=admin receives the same stub as GET /users?role=viewer, masking authorization bugs. Guardrail: Require the prompt to specify match criteria for each stub: path, method, query params, headers, and body matchers where relevant. Validate that no two stubs share identical match criteria unless intentionally ordered by priority.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the quality of generated API mocks and stubs before integrating them into a UI test harness. Use this rubric to catch contract drift, missing error states, and over-engineering before they reach production.

CriterionPass StandardFailure SignalTest Method

Schema Contract Fidelity

Mock response body matches the referenced OpenAPI or JSON Schema exactly for the given status code; required fields are present and types are correct

Response fails JSON Schema validation against the source contract; missing required fields or type mismatches (e.g., string for integer)

Automated: Validate generated mock response against the source schema file using a JSON Schema validator in the eval harness

Request Matching Accuracy

Mock matches the correct HTTP method, path pattern, and query parameters; does not match incorrect methods or paths

Mock intercepts a request with a wrong HTTP method (e.g., GET instead of POST) or ignores a required query parameter, causing false-positive test passes

Automated: Send a matrix of correct and incorrect requests to the mock server and assert correct hit/miss counts

Error State Simulation Coverage

Mock includes at least one 4xx and one 5xx error scenario with realistic error body structure (e.g., Problem Details RFC 7807)

Only happy-path 200 responses are defined; no way to trigger an error state in the UI test, masking error handling bugs

Manual Review: Inspect the generated stub file for the presence of non-2xx response mappings with valid error schemas

Stateful Scenario Sequence Integrity

Stateful mock correctly transitions between states (e.g., 'empty', 'single item', 'full') based on request sequence and returns the correct response for the current state

Mock returns a response for a state that hasn't been reached yet or fails to reset state between test cases, causing cross-test contamination

Automated: Execute a sequence of API calls against the mock and assert the response body matches the expected state at each step; run twice to verify idempotency

Response Latency and Realism

Mock includes a configurable simulated delay (e.g., 50-300ms) to mimic network latency and prevent false-positive UI timing bugs

Mock responds in <5ms, causing UI tests to pass that would fail against a real backend with normal latency (e.g., loading spinners not appearing)

Automated: Measure the round-trip time of a mock request and assert it falls within the configured delay range ±20ms

Mock Complexity Justification

The number of mock scenarios and response variants is proportional to the UI states being tested; no unused stubs

Stub file contains dozens of response variants for edge cases not reachable by the UI, or duplicates logic already covered by API contract tests, increasing maintenance burden

Manual Review: Map each mock scenario to a specific UI test case or user story; flag any unmapped stubs for removal

Dynamic Response Templating Correctness

Dynamic fields (e.g., timestamps, UUIDs, pagination cursors) are generated fresh for each request and are valid according to their format

Hardcoded timestamps or IDs cause duplicate key errors in the UI or fail validation; pagination cursors do not change between requests, causing infinite loops

Automated: Make two sequential requests to the same mock endpoint and assert that dynamic fields have different, valid values

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Strip the prompt down to core stub generation. Remove stateful scenario sequences, contract drift checks, and complexity warnings. Focus on producing a single mock endpoint with request matching and a static response template.

code
Generate a mock API stub for [ENDPOINT_PATH] that matches [HTTP_METHOD] requests and returns:
[RESPONSE_BODY]

Watch for

  • No error simulation (only happy-path responses)
  • Hardcoded response bodies that won't survive schema changes
  • Missing content-type headers causing client parse failures
  • No guidance on mock server framework (WireMock, Mock Service Worker, etc.)
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.