Est.

Replacing Per-Call Mocks With a Single Stateful API Simulator in CI

A single Dockerized simulator tests real API lifecycles, not isolated responses.

· 8 min read
Cover illustration for “Replacing Per-Call Mocks With a Single Stateful API Simulator in CI”
Integration Testing · November 13, 2026 · 8 min read · 1,757 words

To test an application against stateful APIs without hitting production, run one isolated, Dockerized API simulator in CI and exercise complete request lifecycles against it. The simulator must keep state across calls, allow only valid transitions, and trigger events when those transitions occur. Per-call mocks remain useful for unit tests, but integration tests need a shared model of API behavior.

Why per-call mocks are the wrong unit of abstraction for integration testing

A four-step payment test exposes the difference immediately. POST a payment with status “pending”, GET it back, POST a capture, and GET it again. A stateful sandbox returns “captured” on the final read because the capture changed the payment. A per-call mock returns whatever that route was configured to return, usually still “pending”. The capture and the read have no causal link.

That missing link is an architectural defect for integration testing. A static mock maps a given path to a given response, with no memory of the previous call. This design suits a test that isolates one function, checks request headers, or proves that a component handles a particular response. Integration tests ask a different question. They need to establish whether the state produced by call A shapes the response to call B, which requires testing the relationship between operations.

What "stateful" actually requires a simulator to do

Persistence is necessary, but it is not enough. A stateful simulator must enforce a state machine so that invalid sequences are rejected. Its webhooks must fire because a state transition occurred. Its wire format must also match the real API across specification-derived paths, including those beyond a developer’s configuration. Together, these capabilities define a consistent lifecycle that tests can exercise.

With request validation, input manipulation, and calculated responses, the simulator can respond to what the application actually sends. Keploy’s simulation explainer describes a simulated API as an independent process that responds dynamically to request input, can retain state across calls, and can fail on demand. That combination extends its use beyond isolated unit tests into development, QA, and CI.

How the stateful vs. stateless gap produces silent, production-only failures

A passing mock-based integration test can validate the developer’s configuration while leaving the API’s behavior untested. That distinction creates a dangerous kind of confidence. The test may pass for months and immediately before a release, while production fails because the API enforces an omitted constraint or mutates state differently. A newly created entity may also show up in a real list endpoint while the mock keeps returning the same fixed collection. Every configured response can look correct in isolation while the workflow remains wrong.

Asynchronous checkout makes this gap harder to ignore. The application initiates a payment intent, receives a synchronous response, and then relies on a webhook to fulfill the order. A static stub has no transition that causes that event, so it cannot establish whether the choreography is correct. A rate-limit response with a Retry-After header midway through the flow adds another dependency on what has already happened. Multi-turn agents face the same problem more acutely because their later tool calls depend on earlier results, but the underlying requirement is unchanged.

How to test stateful APIs in CI with one Dockerized simulator as the single external contract

The canonical architecture replaces scattered per-call fixtures with one simulator running as a Dockerized service job. The test suite uses it as the external API throughout the run, so writes, reads, and events share one model of state. The simulator starts before testing and is destroyed when the job completes. The integration run makes no calls to a live endpoint. It therefore avoids live rate limits that create false positives, third-party sandbox downtime, and silent schema changes in shared environments.

In practice, startup must be verified in CI logs before the suite is allowed to run. The simulator version belongs in the dependency manifest so that an update does not silently change test behavior mid-sprint. Parallel execution requires isolation as well. Each CI job, developer, or agent needs its own session so concurrent runs cannot corrupt one another’s state.

Integration tests that use the simulator run on every pull request without an external dependency. Real API smoke tests run only on merge to main, where they serve as a release gate. Verification against the provider remains part of the architecture.

What this pattern looks like for specific APIs — Stripe, GitHub, Resend, Slack, Kalshi, PayPal

Stripe illustrates why lifecycle depth is the useful measure. Capture must also change the payment’s state, as the four-step test demonstrates. The simulator needs to represent the transitions and failure paths the application depends on.

GitHub shifts that emphasis toward webhook behavior. Integration testing needs realistic retries, duplicate deliveries, replay, signature verification, and out-of-order events without production keys or real repository data. Resend presents a related lifecycle through transactional email. A stateful simulator can cover idempotent sends and webhook events for delivered, bounced, and opened states without sending real email, consuming quota, or affecting an inbox.

Tests of Slack bot interactions, Kalshi prediction market order flows, PayPal payment authorizations, and Lob address verification all work better when state stays consistent. OpenAPI-spec-driven simulators can extend coverage to APIs that publish an OpenAPI 3.x specification. That provides a route to broader coverage as integrations grow. It does not remove the need to assess each API’s operation-specific logic, because a broad catalog of routes is not equivalent to a deeply modeled lifecycle.

Why AI agents and RL environments need stateful simulators more than conventional test suites do

Agents amplify the effects of inconsistent state because they use tool responses to decide what happens next. An agent may treat an error response as if it contained valid results and fabricate data to fill the expected shape. A successful HTTP fixture cannot reveal that failure. Testing it requires a fault at the tool boundary and observation of whether the agent acknowledges or conceals the failure. State in the session must stay consistent so later actions can be checked against what actually happened.

For RL environments, writes must affect later reads, shared state must stay consistent across tool calls, and the environment must scale horizontally as more agent instances run in parallel. Recorded cassettes and stateless mocks cannot satisfy those requirements together. A stateful simulator provides controllable state for deterministic runs while supporting isolated parallel sessions. Fault composition extends the test further by combining, for example, an LLM rate limit with a tool timeout in the same session.

Routine CI and load testing of agent tool-use belong against the simulator, where application logic and state handling can be exercised without live-provider dependence. Real provider calls are still needed to test how the model behaves and how well the prompts work. A simulator cannot measure the current quality or variability of a live model.

Fault injection as a first-class concern, not an afterthought to happy-path testing

A stateful simulator that tests only successful flows leaves resilience unexamined. A payment timeout after two successful steps is meaningful only if those steps have already changed the simulator’s state. Likewise, a webhook that arrives out of order must remain connected to the lifecycle that produced it.

Latency simulation, 429 responses with Retry-After headers, and 503 transient failures are baseline requirements for resilience testing. Their placement within a sequence determines what the application must handle. A user session that becomes invalid mid-flow, for example, tests a different condition from one that was invalid from the start. For multi-agent systems, faults must also reach agent-to-agent communication, LLM calls, and tool interactions. Testing only one boundary leaves the other two unexamined.

Simulator drift: why a stateful simulator must itself be continuously verified against the real API

The most dangerous simulator failure is a passing test against incorrect behavior. A simulator can remain internally consistent while no longer matching the provider. Research on RL environments documented a sandbox with four silent discrepancies, including unrecognized query syntax returning empty results rather than errors, misspelled field names being ignored, identical plausible figures for every portfolio reference, and records stored in generation order. Each discrepancy affected agent behavior while appearing to be a legitimate response. An audit found the failures while the tests kept passing.

A specification reduces this risk without eliminating it. Spec-driven tools drift more slowly than hand-maintained ones, but a provider can change its implementation without updating the published contract. The simulator then preserves the wrong behavior faithfully. This is the gap between specification and wire behavior, and internal test consistency cannot close it. Automated checks against the live API’s actual responses before each simulator release catch drift at release time, before it can cause a surprise in production.

Verification also defines the limits of fidelity. A simulator can validate that the right sequence of calls produces the right state transitions without reproducing every vendor-specific business rule. A payment capture flow may work correctly while a particular test card’s decline mapping remains absent unless it has been explicitly verified and encoded. That boundary must remain visible to teams interpreting results. Fidelity scores published with releases provide an objective signal of the match with live behavior, rather than leaving confidence to the simulator’s presentation.

Where per-call mocks still belong and how to run both in the same pipeline

Per-call mocks remain appropriate for isolating a function, asserting that an HTTP request used specific headers, or supplying a deterministic response without state coupling. They also help when a third-party dependency has no public specification. These cases make up a large part of unit testing. Keeping mocks there is efficient because those tests do not require a model of an external lifecycle.

The simulator occupies the space between those isolated checks and a final check against the real service. It tests whether operations compose into a valid workflow, while the live smoke test checks that the modeled behavior still agrees with the provider. Neither removes the other’s purpose. Teams with multi-protocol dependencies, including message queues, JDBC, and JMS, may need service virtualization as a further tier. The simulator can meet most HTTP-only integration needs without a full service virtualization platform.

The resulting pipeline has three distinct gates. Unit tests that use mocks run on every commit, take less than a second, and need no infrastructure. Simulator-backed integration tests run on every pull request with isolated state and no live credentials. Real API smoke tests run on merge to main over a minimal surface, checking for divergence from the provider’s current behavior. Each layer answers a different question, from local response handling to lifecycle correctness to agreement with the live service.

Diagram: Three-Gate Testing Pipeline. Visualizes: Show the three-stage CI pipeline described in the article as a horizontal flow with three distinct gates, each labeled with its trigger, tool, and what question it answers.

More in Integration Testing