Payments PendingPinning Payment Simulator State so Charge Sequences Reproduce Identically Across CI Runs

Pinning Payment Simulator State so Charge Sequences Reproduce Identically Across CI Runs

Restoring a full simulator snapshot before each sequence makes payment tests repeatable.

· 8 min read

Integration testing against stateful APIs requires a simulator that preserves changes between calls and restores a complete, known starting state before each sequence. For payment workflows, pinning test cards is insufficient. Pin the customer, payment method, relevant charge history, subscription state, idempotency records, and asynchronous delivery state so that each run tests the same preconditions and valid transitions without moving production funds.

Why charge sequences fail to reproduce in CI even when test cards are correct

A charge test passes repeatedly, then fails when the suite changes order or another test runs in parallel. The card number has not changed. The false assumption is that the card determines the sequence, when its outcome also depends on resources left by earlier calls. A customer’s charge history, an attached payment method, or an already-consumed idempotency key can change what the next request does.

Adyen’s Payment Simulator description identifies three causes of payment-test failure. The conditions were outside the test’s control, the assertion checked only the first response, or the assertion omitted the merchant state that should follow the outcome. State pinning addresses the first cause, but assertions must address the others. A correctly shaped first response does not establish that webhook handling, persistence, or downstream checkout state works.

What "simulator state" actually encompasses for a payment sequence

Simulator state covers every resource that a sequence reads or writes. For a Stripe charge sequence, that includes the Customer and its metadata, the attached PaymentMethod, and prior PaymentIntents with their statuses and captured or uncaptured condition. Recurring billing adds Subscription and Invoice resources. Consumed idempotency keys and webhook delivery state also belong to the sequence when they affect subsequent behavior.

The boundary extends beyond the synchronous API response. Adyen describes UPI Intent as returning a pending response, with the result established only when the integration receives an AUTHORISATION webhook. Treating pending as final shortens the test but also changes what the workflow does. A basic card payment can finish in one request-response exchange, while redirect-based and QR-based methods pause at different points in the lifecycle. The required state surface follows those continuations.

How stateless mocks fail multi-step charge sequences by design

A stateless mock cannot enforce a transition because it has no memory of the state before it. A mock that always returns “captured” can report success before a PaymentIntent has been confirmed, accepting a sequence the real API would reject. Scripted responses bind results to call order, require maintenance as the integration changes, and do not establish that an invalid transition produces the documented error. With stateful simulation, the response depends on the state the resource is in. Its purpose is to test valid transitions and rejected transitions.

State leakage across CI runs: how accumulated simulator state makes sequences non-reproducible

Consider a sequence that reuses a customer and an idempotency key from an earlier run. The simulator still has the earlier charge history and registered key, but the test expects a fresh starting point. The same request now encounters different preconditions. Run alone against clean resources, the sequence passes, but after the earlier test it follows a different path.

Stripe’s testing documentation warns that card-level state can change how later tests with the same card behave. It recommends a different test card for each independent end-to-end scenario when the test depends on card-level state. Customers, PaymentIntents, subscriptions, and delivery queues can still retain history independently of the card.

The remedy is per-sequence reset and isolation. Resetting only at the start of a CI job leaves sequences within that job able to interfere. Parallel execution makes shared resources especially problematic because one sequence can change them while another is using them.

What to snapshot: the minimum complete state unit for a charge sequence

The snapshot should hold exactly the resources the sequence touches, each in the state it needs to be in before the call. For the Customer, pin the ID, metadata, and default payment method pointer. For the attached PaymentMethod, pin its type and the card fingerprint when relevant. Any prior PaymentIntent that controls a branch needs an explicit status set for the current run. Subscription scenarios also need the relevant Subscription and Invoice objects.

Idempotency needs request keys that stay the same and a known registration state for those keys. Derive each submitted key from the fixture ID and operation name. A retry can then reuse the same key and retrieve the cached result of an operation already performed. A new random key instead identifies a new operation and can permit duplicate execution.

Snapshot scope is the isolation boundary. An account-wide snapshot includes unrelated resources and makes sequences interdependent, while an incomplete snapshot leaves hidden inputs uncontrolled. For asynchronous workflows, the complete unit also includes delivery state, so that pending messages from another execution cannot enter the sequence unnoticed.

When to restore state: the restore-before, not restore-after, discipline

Restore the snapshot before each sequence begins. Cleanup after a test assumes that the test reaches its cleanup step, which a failed, cancelled, or interrupted CI process may not do. The next sequence should not inherit that assumption.

This can run in a setup fixture or beforeEach hook. The simulator needs a reset endpoint or snapshot-load command fast enough that restoration does not dominate CI time. For webhook-dependent workflows, restoration must cover the pending-webhook queue as well as synchronous resources. Otherwise, an earlier run’s message can arrive after setup and alter the new run’s assertions.

Setup establishes the initial condition, while subsequent calls must retain their effects throughout the sequence. Resetting between those calls would erase the very transitions the test is meant to examine.

What breaks when state pinning is skipped: failure modes ordered by how hard they are to diagnose

The first and most visible failure is an immediate resource mismatch. A customer is missing, or a PaymentIntent exists in the wrong status, because the simulator reflects another run’s side effects. The assertion fails close to the cause. Diagnosis still requires inspecting state, but the mismatch is visible within the failing sequence.

The second failure is order-dependent behavior. A test passes alone but fails after a particular predecessor, making execution history part of the diagnosis. Parallel runs complicate that investigation further because shared-resource changes need not occur in a stable order. Repeatedly rerunning the test can conceal the dependency.

The third failure is silent branch omission. Accumulated state enables only some paths, so the suite passes without exercising behavior that requires a fresh starting point. The defect can survive into production. Adyen’s pending-response example shows why final-state assertions are also necessary, since an integration that ships an order before the payment outcome is established has a bug even if its first response passes schema checks. Pinned preconditions make the intended path reachable, and lifecycle assertions establish whether the integration handled it correctly.

Applying state pinning to a Stripe charge sequence: a concrete walkthrough

Stripe’s testing documentation establishes that test API keys operate in a sandbox where transactions do not move funds. Stripe also supports up to five isolated sandboxes, but environment isolation does not restore resources between runs. A sandbox can accumulate state just as a simulator can. The following capture-then-refund scenario therefore uses a simulator fixture rather than assuming that a separate environment is a clean one.

First, define a fixture in which the Customer exists, its PaymentMethod is attached, and the PaymentIntent is in requires_capture. Pin the relevant idempotency registration state and the keys the sequence will submit. The intermediate status is decisive. Starting from requires_confirmation or succeeded makes the capture call test an error path, leaving the intended successful transition untested.

Restore that fixture before the first call. Submit the capture using a key derived from the fixture ID and operation name, such as fixture-42-capture. Then assert that the simulator resource reflects the captured condition, rather than accepting only a successful response shape. The assertion establishes the precondition for the refund call.

Next, submit the refund against the captured charge using its own stable operation key. Assert the resulting resource state and the merchant state that should follow the refund. These checks distinguish a coherent sequence from two independently successful responses. If the scenario also depends on asynchronous confirmation, trigger the required webhook at a controlled point and assert the integration’s state after it handles delivery. For subscription scenarios, the fixture must additionally include the Subscription and its current Invoice.

Extending the pattern to recurring billing and subscription state machines

Stripe’s API reference lists subscription statuses including incomplete, incomplete_expired, trialing, active, past_due, canceled, unpaid, and paused. Each status changes which subsequent events are valid. Mandate lifecycle state must also be explicit, because attempting to charge a cancelled mandate is a state-machine error that a favorable default fixture can hide.

Invoice state adds another independent precondition. Before a charge attempt, pin the invoice to open and derive the charge’s idempotency key from the invoice ID. For broader transition coverage, property-based testing can exercise seeded sequences of subscribe, charge, pause, resume, and cancel operations. The seed makes the random ordering reproducible, while the pinned starting state makes invariant failures attributable to the sequence.

Fault injection requires pinned state to be meaningful

Fault injection introduces a controlled disturbance into a known workflow. Without pinned state, a test could fail because of either the injected fault or a starting condition the test did not expect. That ambiguity weakens the result before retry handling is examined. Rate limits, 429s, 503s, timeouts, and partial responses therefore belong in tests whose resource state is already deterministic.

For a charge sequence, a 429 tests whether a retry preserves the idempotency key and avoids creating a duplicate operation. A lost response after successful confirmation tests whether the integration can recover an outcome that has already been committed. Webhook delivery failure tests whether the integration handles failed delivery by polling or retrying. Resource assertions are essential in each case, including when a 200 response contains stale or incorrect state.

LuisDeveloper-Fer’s payment-simulator shows the LOST_RESPONSE case by committing APPROVED state and returning 504. A query by idempotency key then returns APPROVED. The response failure and committed payment are deliberately different observations of the same operation. Pinning both the state and the fault makes that distinction testable, which makes state pinning a correctness requirement that also reduces flaky CI runs.

How can a simulator make integration testing against stateful APIs practical in CI?

A practical simulator needs a named-fixture snapshot-and-restore API and per-sequence namespaces. Customer ID prefixes, headers, or ports can keep sequences separate when they run in parallel. Restoration must be cheap enough to run before every sequence. Otherwise, the suite is pushed back toward sharing history or cleaning up by hand.

The simulator must also register idempotency keys, return cached results on replay, and enforce the API’s transition rules. An invalid operation must produce the documented error. Asynchronous workflows require webhook delivery on demand, while resilience tests require latency, 429s, 503s, and LOST_RESPONSE to be selectable per call or sequence. These controls let the test set the starting condition and the fault while leaving the integration’s own behavior in place.

Continuous verification against the live API is the remaining requirement. A simulator that drifts from the real contract undermines assertions even when its fixtures reproduce perfectly. For integrations with Stripe, PayPal, or other supported APIs, a live sandbox offers a different trade-off, including accumulated state, rate limits, and live credentials. A hand-rolled stateless mock sidesteps that environment but cannot enforce resource transitions.

Sources

  1. Test card numbers

More in Payment Flow Testing