Common Failure Modes When Mocking Stateful APIs
Stateless mocks fail to catch bugs in workflows that depend on accumulated state.

Integration testing against stateful APIs requires a test environment that persists resources, enforces valid transitions, and remembers prior requests without hitting production. Common failures when mocking these APIs stem from one category mismatch, namely using memoryless request-response mappings to test workflows whose correctness depends on accumulated, ordered state. A stateful simulator closes that gap only when it also validates relationships, models failures, and stays aligned with the real API.
Why stateless mocks and stateful APIs are a category mismatch, not just a tooling gap
A stateless mock is effectively a configuration file. It matches a request path or body shape and returns a defined response, but it does not remember what happened before that request. A stateful API, by contrast, answers within a world that earlier requests have changed. Its response depends not only on what the caller asks now, but also on which resources exist and what operations have already occurred. Better fixture configuration cannot remove that structural difference.
An order moving through CREATED → PAID → SHIPPED → DELIVERED makes the distinction clear. Endpoint success alone does not establish workflow correctness. The system must stop shipment before payment, avoid double-charging on retries, and keep state valid when concurrent updates occur. A sequence of compatible fixtures may look consistent because the engineer supplied that consistency.
The diagnostic is a short sequence of dependent operations. Create a resource and read it, then mutate it and read it again. Each response must take into account what earlier requests changed, even when an answer has been configured on its own. If a tool cannot pass that “create then read, mutate then read” test, it qualifies only as a mock for the workflow.
How phantom resources expose the first consequence of memoryless mocks
The most immediate failure appears when creation and retrieval disagree. A call to POST /charges returns {"id": "ch_123"}, but a subsequent GET /charges/ch_123 returns 404 because the mock stored nothing. Each request was handled independently, so the successful POST imposed no obligation on the GET. This reflects missing persistence.
Configuring the GET to return a hardcoded charge object removes the visible contradiction but not the defect. The object still has no causal relationship to the POST. It shows up even if creation failed, the caller used the wrong ID, or a conditional write never happened. The fixture becomes a phantom resource because it makes the resource look as though it exists even though the earlier operation never made it so.
Code that charges a stored card, ships a created order, or updates a provisioned subscription assumes that the resource exists before the next operation starts. A fixture can satisfy that assumption without testing it. The resulting test passes because the read side supplies the expected object, while the production path can fail silently because there is nothing to operate on.
Broken state machines: when valid transitions and forbidden ones look identical to a mock
A resource can exist and still be in the wrong state for the next request. When a mock returns its fixture for POST /shipments regardless of whether the order is CREATED or PAID, it omits the transition guard that makes payment a prerequisite for fulfillment. A bug in the caller’s payment check consequently produces no rejection in the test.
The same pattern applies to refunds, subscription cancellations, and auth-capture payment flows. Each permits some orderings and forbids others. Stripe’s payment lifecycle illustrates the distinction through an auth-capture pattern in which capture depends on the PaymentIntent being capturable. A mock that returns success for POST /refunds on an uncaptured PaymentIntent similarly hides an invalid operation that the real API rejects. The missing rule causes this failure across endpoints.
Separate tests for each state do not resolve this. An isolated test configured with CREATED and another configured with PAID can verify how the caller handles those supplied responses. Neither shows that the system will reject a move between states that its rules forbid. To test transition enforcement, a test must try the illegal operation as part of a sequence and check that it is rejected because of the state the earlier steps created. The environment must remember the resource and apply the rule to it.
Invisible idempotency bugs: the failure mode that only appears on retry
A payment request can succeed even when a network timeout prevents the caller from receiving the response. The caller retries, creating the risk of a double charge if duplicate processing is not prevented. A stateless mock returns a success fixture for both calls. That result says nothing about whether the second request repeated the operation or recovered the result of the first.
Stripe and PayPal use idempotency keys to distinguish a retry from a new operation. The server must remember those keys from one call to the next for the protection to work. Stripe saves the first request’s result and returns it for subsequent requests with the same key. A real server can therefore prevent the second charge, while the mock offers no evidence that the caller exercised that protection correctly.
The reverse failure is just as dangerous. Code may assume that an endpoint is retry-safe without checking for duplicate processing, so a double-write or double-send bug stays hidden as the fixture returns success each time. A test that explicitly issues a retry can still miss this defect because the mock cannot distinguish replaying a result from performing the operation again. The test contains two calls, but no model of their relationship.
Webhook handling has the same dependency on history. A stateless mock that fires one event does not model retrying delivery after failure or deduplicating duplicate deliveries. It can exercise the handler’s response to that event without establishing that the handler is idempotent. Retry safety requires testing what happens after prior delivery attempts.
False-passing multi-step flows: how a green test suite can coexist with broken integration logic
Independent fixtures can make an entire integration flow pass without validating the connections between its steps. One request creates a customer, another creates a subscription for that customer, and a third invoices the subscription. Every endpoint returns success. Yet the mock never checks whether the subscription references an existing customer or whether the invoice references an existing subscription. The sequence runs, but its referential integrity remains untested.
This combines the earlier failures into a misleading end-to-end result. Stubs that cover only the happy path also leave out the failures that should trigger error handling. A passing suite can consequently coexist with broken production error handling for months before a real failure exposes it. More successful steps do not strengthen the evidence if each step rests on an independent fixture.
State leakage in CI adds a separate source of ambiguity to that false-green signal. Even when response mappings have no memory, tests can share state from the scenario around them that is not reset between runs. If tests behave differently individually and in parallel because of that leakage, their results depend on execution order. The suite becomes non-deterministic as well as incomplete. QA teams confronted with flaky or misleading pipelines can lose trust, begin ignoring red builds, and miss real defects, a dynamic also driven by flakiness from live API coupling.
The diagnostic is to test a deliberately broken relationship. Run the full sequence against a tool that persists state, then create a customer and attempt to subscribe using a different, nonexistent customer ID. The subscription attempt must fail because its prerequisite is absent. If it succeeds, the tool cannot validate referential integrity, and the green result is not evidence that the integration works.
Silent drift: how a mock that was accurate at writing becomes a liability over time
A mock can match the API when it is written and still mislead later. The real API changes while the hardcoded fixture stays the same. Each contract change that affects the stub needs to be added by hand, but the old fixture can still pass every assertion. This failure preserves a green result for a contract the production integration no longer receives.
With Stripe’s 2025-03-31.basil release, shipping_details moved from the top-level Checkout Session object into collected_information.shipping_details. A test with the old field layout would still use the old access path. It would not expose the mismatch when the integration began receiving the new shape in live webhook payloads. Fixtures built around the Checkout Session resource needed to use the field’s new location.
Version management makes this more subtle than updating one fixture. The webhook endpoint API version, the event api_version, the account default, and the pinned SDK version are separate values that require deliberate alignment management. They do not always have to match. A null api_version on a registered webhook endpoint means the account default controls payload shape, so a later account upgrade can change payloads without a corresponding webhook-code deployment.
The dangerous mock is therefore often the plausible one. A fixture based on a six-month-old schema can look right and pass its tests while production code fails on fields that were renamed, moved, or removed. The fixture can ignore both the links between requests and changes to the contract because it stands on its own. Without verification against the real API, passing tests establish only agreement with the mock.
How can integration testing against stateful APIs use simulators to close the gap?
The failure taxonomy defines concrete requirements for a stateful simulator. Persistence must make a created record available to subsequent reads, lists, and deletes, and deletion must make it disappear. Transition enforcement must stop an order from moving from CREATED to SHIPPED unless it has passed through PAID. A tool that stores an order still needs rules for when shipment is allowed.
The tool must track idempotency keys across calls, process the operation once, and return the cached result on a retry. Webhook delivery must model retry-and-deduplication semantics so tests can exercise repeated attempts. Multi-step workflows also require referential integrity. A subscription referencing a nonexistent customer must fail because of that missing relationship.
Correctness testing must share an environment with resilience testing. First-class fault injection needs to cover latency, 429s, 503s, timeouts, and malformed responses so the caller’s behavior under failure can be tested within the same stateful workflow. Otherwise, a successful sequence still leaves its recovery paths unexplored. To address drift, the simulator must also be continuously verified against the real API before every release. Fidelity must be measured and published rather than inferred from how convincing its responses look.
AI agent and RL evaluation environments impose the same requirements more stringently. Agents calling tools in sequence need deterministic behavior, horizontal scalability across many containers, and a simulator that reflects the cumulative state of prior tool calls. An evaluation cannot reliably judge the order of calls if each answer ignores what the earlier calls did. Platforms such as Rystic, a locally runnable stateful simulator that maintains cumulative state across sequential API calls and is continuously verified against the real API before each release, are built to meet exactly that standard. The decisive criterion is whether the test environment can reject a workflow that is wrong because of what happened earlier.


