Stateful vs. Stateless Auth Mocking in Integration Test Suites
Stateless auth mocks pass revoked tokens, so only verified stateful simulators catch the bugs.

For integration testing against stateful APIs without hitting production, use a simulator that stores state, enforces operation order, and is verified against the real API before release. Authentication makes the distinction clear because issuing, validating, refreshing, and revoking tokens are linked transitions. Stateless auth mocks test configured responses, so a passing suite can conceal broken token handling.
Why auth flows are sequential and stateless mocks cannot follow that sequence
An authentication sequence begins when a service issues a token. The client then presents it for bearer validation, refreshes it before expiry, and revokes it on logout. Each operation depends on what came before it. Validation must recognize a token that was issued, refresh must check its current status, and logout must change what later requests can do. These are transitions in a shared state machine.
That dependency distinguishes auth testing from checking a response in isolation. A validation request can look identical before and after revocation, yet require a different result. History determines the correct response in this case. A stateless mock has no record of that history because it matches a request to a configured response without remembering what earlier calls changed. Hardcoded validation success therefore establishes neither that a token was issued nor that it remains usable.
What a stateless mock actually does during an auth sequence, step by step
A stateless mock maps a method and path to a response body. In the first step, POST /token returns a hardcoded access token. In the second, GET /validate returns a hardcoded body reporting that the token is valid. Those responses share no record of token issuance. Their relationship exists in the test author's configuration.
The third step, POST /token/revoke, exposes that separation. The mock returns its configured success response but records no revocation. In the fourth step, another GET /validate matches the same rule as before and reports that the token is valid again. The request matches, but the result is wrong. A real API enforcing revocation, or a stateful simulator of it, returns 401 for that final validation.
A test that accepts the final success response therefore passes without exercising the effect of revocation. The same lack of memory hides cases where signing-key rotation or server-side session invalidation would cause a request to be rejected. The configured response does not depend on either event. Production can then reject legitimate users or accept invalidated sessions despite a green integration suite.
How token expiry and session invalidation expose the stateless mock's memory gap
Token expiry requires both a recorded lifetime and a clock against which to evaluate it. A stateless mock can return an expires_in field without enforcing any deadline. The field describes time but does not enforce it. Validation can keep succeeding indefinitely because the mock never compares the token's expiry with the current time. Such a test cannot show whether the application refreshes credentials when their lifetime ends.
Session invalidation reveals the same gap without waiting for time to pass. Logout must change the status of an existing session so that later requests lose access. A canned logout response changes no shared record. To catch broken session management, a test also needs to know which user owns the session and what earlier interactions allowed. Without that context, a suite cannot expose privilege failures simply by matching well-formed requests.
Kalshi illustrates why authentication checks also need protocol-specific behavior. Kalshi uses RSA-PSS rather than HMAC or RSA PKCS#1 v1.5, and its randomized padding means signatures of the same payload do not match. Separately, Kalshi rejects timestamps too far from server time but returns the same opaque 401 whether the key is wrong or the clock is off. A container with a frozen clock can fail authentication even if the rest of the code is correct, while a mock that checks neither signatures nor timestamps reports success.
How do you write integration tests for auth APIs where order matters?
A stateful auth simulator needs a store of issued tokens and their metadata, including issued-at time, expiry, scope, and owning user. It also needs a record of revoked or invalidated tokens and the current session state per user. Validation must check those records on each call. An expired token must fail even when its request is well-formed, and a revoked token must remain unusable regardless of whether its signature otherwise passes validation.
Mutating calls must update the state that later calls read. Revocation must remove or invalidate the token in the shared store, while refresh must succeed only when the refresh token is valid and unrevoked. The simulator must distinguish an allowed transition from an operation that merely has the expected method, path, and body. Those constraints belong to the API's behavior.
In the four-step sequence, POST /token followed by GET /validate must pass validation, while POST /token/revoke followed by validation of the same token must return 401. A second validation returning 200 fails that requirement. Pre-seeded sessions and tokens let tests begin mid-flow without rebuilding every prerequisite manually. That seed data must still participate in the same state machine, so starting with an existing session does not bypass expiry, ownership, or revocation checks.
Why drift from the real API quietly invalidates a stateful simulator over time
Stateful behavior is necessary, but it is not permanent proof of fidelity. A simulator can enforce yesterday's rules correctly while diverging from today's API. The tests still pass against the wrong contract. A changed token format, required claim, or revocation rule can make the simulator accept credentials the service rejects, or reject credentials the service accepts. This produces the same false confidence as stateless mocking through a different mechanism.
The open-source slack-web-api-client project shows the work it takes to keep up through automated drift checks against Slack's official changelog, the Java SDK MethodsClient, and the pinned version in the client that uses it. Its August 2026 checks included the agent_session_title_changed event, ChatStopStreamRequest missing session_status, and the agents.sessions.setStatus and agents.sessions.rename methods. The event and methods were resolved in v1.1.15, released October 13, 2026. Even a governed process can accumulate a backlog. These changes outside auth demonstrate why maintaining agreement with an upstream API requires both automation and discipline.
Automated schema diff jobs provide one part of that countermeasure. They compare registered simulator behavior with the service's current OpenAPI or AsyncAPI contract and flag field additions, removals, and type changes before they reach CI. Checks of behavior must cover the auth transitions too. A simulator verified against the real API before every release can detect discrepancies that hand-maintained responses leave open. By contrast, a spec-driven response generator inherits a stale or incomplete specification without gaining any memory of token state across calls.
How auth mocking fits into a CI pipeline and where stateless mocks create pipeline-specific failure modes
Parallel test workers magnify the consequences of shallow auth behavior. When every worker receives the same hardcoded token, one worker's revocation call does not change what any other worker receives from validation. Ephemeral environments add a related requirement because destructive expiry and revocation tests need state that belongs to their own run. Without per-environment state, there is no session history to isolate.
For teams running these tests in CI, the recommended pattern is one environment per pull request, torn down when the pull request closes. That gives destructive tests a boundary separate from other runs. Credentials should be short-lived federated tokens, with OIDC first. Their lifetime is part of the test contract. A mock that cannot validate expiry or enforce OIDC claims cannot verify code that depends on those credentials.
Pipeline gates should block contract-test failures and schema-drift breakages, while flaky-test thresholds should warn without blocking. A revoked-token check that always returns 200 cannot show that the contract it was meant to test is broken. At the other extreme, a detailed simulator with poor isolation can leak secrets or mask dependency outages.
Fault injection as the final test of an auth simulator — simulating 401s, token expiry, and replay attacks
Auth fault injection tests recovery at a particular transition. A simulator can expire a token mid-session to test refresh, or revoke it during a multi-step flow to test whether the client stops using stale credentials. A 429 on refresh tests backoff, while a 503 on revocation tests handling of failure at a different operation. These failures need to be addressable at specific flow points.
Latency on the token endpoint is a distinct fault class. A slow response tests whether the application times out, retries with backoff, or hangs. Plausible responses can be more dangerous than obvious errors. AgentChaos found that runtime faults injected into API responses that never raised an error were among the most dangerous and hardest to diagnose across tested agent systems. For auth testing, that finding reinforces the need to check the resulting state and whether the client received an error.
Payment flows add retry and acknowledgment behavior to that requirement. Stripe can retry undelivered webhooks for up to three days, while PayPal requires HTTP 2xx acknowledgments. Endpoint outages can therefore affect more than one delivery. Tests for these flows should cover outages, how replays are handled, and reconciliation that can be traced across the retry window before happy-path results can be trusted. A stateless response cannot model the time-dependent history that distinguishes an initial delivery from a replay.
A generic injected 401 is not equivalent to enforcing expiry. The latter must identify the token issued earlier and reject it once its lifetime ends. Replay rejection likewise depends on recognizing prior use. Although a fixed response can imitate an error, it cannot establish that the error follows from the correct transition. State-dependent fault injection requires the same token identity, time, and interaction history as correctness testing.
Auth state machines in AI agent testing — why tool-calling agents make stateless mocks even less viable
A tool-calling agent faces the same auth state machine as any other API client, but API responses also guide its subsequent decisions. A correct-looking tool call can still present an expired or revoked token. A canned success then validates the wrong continuation. Downstream logic may act on a plausible response that the real API would never have supplied. The gap concerns both credential handling and the decisions made from its apparent outcome.
For agent evaluation, the recommended pattern is to mock the model and test the logic. A deterministic model mock returns fixed JSON while the agent's token handling, refresh, and recovery run against a stateful API simulator. This separates model output from enforced access rules. Scope and session ownership also make security tests meaningful, including unauthorized calls induced by prompt injection, data extraction with an over-scoped token, and session fixation. A response matcher that keeps no state for ownership or permissions cannot test those boundaries.
The MCP 2026-07-28 specification introduces a complication by replacing bidirectional session state with a stateless request/response core. It retires initialize and Mcp-Session-Id, adds per-request _meta and header-based gateway routing, and introduces MRTR for mid-call user input. Transport statelessness does not erase application auth state. The transport forgets the agent after each request, while explicit handles passed on later calls point to the application's state. Tests must therefore distinguish a stateless transport from tokens, session handles, and permissions that remain stateful across tool calls.
Reinforcement learning environments extend the same requirement to repeated training runs. They need deterministic state, horizontal scaling across containers, and seed data that is realistic enough to use when they reset and replay a run. An empty sandbox supplies none of that automatically. Evaluation also needs a boundary within which tests can run, including local and CI runs without live credentials, rate limits, or a provider account. Offline or air-gapped use depends on that independence, while release-time verification keeps independence from becoming drift.
A suitable auth simulator rejects expired and revoked tokens, enforces refresh rules, and injects faults at specific transitions.


