Skip to main content

Testing Payment Systems

Last Updated: 2026-12-01 Status: Complete

Testing payment systems means proving that money logic is correct under normal flow, repeated requests, partial failures and late or duplicate messages, without ever touching real cardholder data. After this page you should be able to assemble a layered test strategy, choose between a sandbox and a fake for each test, simulate disputes and failures, write a concurrency test for idempotency, and design a sandbox for your own platform customers.

The expensive bugs in payments are not syntax errors. They are a timeout that causes a double charge, a webhook that arrives before its predecessor, a payout that exceeds a balance under concurrency, or a rounding rule that loses one minor unit per thousand transactions. Test for those deliberately.

Quick Reference​

LayerWhat it provesWhere it runs
UnitState machine transitions, fee and rounding mathIn memory, milliseconds
Property-basedLedger invariants hold for any inputIn memory or test database
Contract and fixtureYour adapter understands the processor's response shapesRecorded fixtures, fakes
IntegrationReal database, queues, your own services togetherContainers
Sandbox end-to-endA few critical flows against the processor's sandboxProcessor sandbox, slow
LoadThroughput and bottlenecksYour own simulator, never a processor sandbox
Failure injectionTimeouts, duplicates, disorder, late files behave correctlyFake processor with fault controls
Time-Sensitive

Test-card pages, dispute simulation values and sandbox behavior are vendor features and change. The pages linked below are the source of truth; check them rather than copying values into your tests.

What Does a Test Strategy for Money Look Like?​

A common interview question is how you would test a payment system. A good answer is a pyramid with money-specific additions:

  1. Unit tests for the state machine. For every state and every event, assert whether the transition is allowed and what side effects it produces. Table-driven tests map directly onto the transition tables in State Machines. Include the illegal transitions: capturing a voided payment must fail.
  2. Unit tests for fee and rounding math. Use integer minor units, test the rounding rule on awkward values, and test that distributed fees sum exactly to the total. See Fee Engine.
  3. Property-based tests for ledger invariants. Generate random sequences of operations and assert that every entry balances and that each account balance equals the sum of its lines (see below).
  4. Contract and fixture tests for each processor adapter.
  5. Integration tests with a real database, because isolation, unique constraints and locking behave differently in mocks.
  6. A few end-to-end flows in the sandbox to catch drift between your assumptions and the vendor.
  7. Load tests against your own simulator.

How Do You Test Ledger Invariants with Property-Based Tests?​

An example-based test checks one scenario you thought of. A property-based test states a rule and lets a generator hunt for a counterexample. For a ledger, the rules are stable:

  • Every journal entry sums to zero: total debits equal total credits per currency.
  • A derived balance equals the sum of that account's lines.
  • Posting the same idempotent command twice changes nothing.
  • An original entry followed by its reversal nets to zero.

The sketch below uses fast-check with Jest and a NestJS testing module. The ledger service and its in-memory repository are assumed; the point is the shape of the test.

import { Test } from '@nestjs/testing';
import * as fc from 'fast-check';
import { LedgerService } from './ledger.service';
import { InMemoryLedgerRepository } from './testing/in-memory-ledger.repository';

const accountIds = ['cash', 'merchant_payable', 'fee_revenue', 'reserve'];

// An arbitrary balanced posting: a debit and a credit of the same amount.
const posting = fc.record({
debit: fc.constantFrom(...accountIds),
credit: fc.constantFrom(...accountIds),
amount: fc.bigInt({ min: 1n, max: 1_000_000n }),
}).filter((p) => p.debit !== p.credit);

describe('Ledger invariants', () => {
let ledger: LedgerService;
let repo: InMemoryLedgerRepository;

beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [LedgerService, InMemoryLedgerRepository],
}).compile();
ledger = moduleRef.get(LedgerService);
repo = moduleRef.get(InMemoryLedgerRepository);
});

it('keeps every entry balanced and the trial balance at zero', async () => {
await fc.assert(
fc.asyncProperty(fc.array(posting, { maxLength: 50 }), async (postings) => {
repo.clear();
for (const p of postings) {
await ledger.post({ currency: 'USD', lines: [
{ account: p.debit, side: 'debit', amount: p.amount },
{ account: p.credit, side: 'credit', amount: p.amount },
]});
}
const total = repo.allLines().reduce(
(sum, l) => sum + (l.side === 'debit' ? l.amount : -l.amount), 0n);
expect(total).toBe(0n); // trial balance
for (const id of accountIds) { // balance equals sum of lines
expect(await ledger.balanceOf(id)).toBe(repo.sumOf(id));
}
}),
);
});
});

Also generate unbalanced entries and assert that the service rejects them. A property test that only feeds valid input proves little. See Double-Entry Ledger for the invariants themselves.

Sandboxes, Mocks or Fakes?​

Should integration tests call the processor's sandbox? The trade-off is realism against speed, determinism and availability.

OptionStrengthWeaknessUse for
Processor sandboxClosest to real request validation and response shapesSlow, rate-limited, can be down, behavior differs from live in places, shared stateA small smoke and end-to-end suite, run on a schedule and before release
Mock (stub per call)Fast, deterministicEncodes your assumptions; passes while production breaksUnit tests of one adapter method
Fake (a working in-memory processor you write)Fast, deterministic, stateful, supports fault injectionYou must keep it faithfulMost integration tests, failure injection, load tests
Recorded fixturesReal response shapes without networkCan go staleContract tests for parsing

Contract tests close the gap. Record real sandbox responses (with identifiers and any personal data removed), replay them in tests to verify parsing, and re-record on a schedule. Run the same test suite against both the fake and the sandbox, so a difference in behavior shows up as a failing test instead of a production surprise. Sandbox behavior is not identical to live, so treat a sandbox pass as evidence, not proof.

Load tests belong on your own simulator. Processor sandboxes are rate-limited and are not intended for load testing; check the vendor's terms before generating volume against one. Build the fake to answer with configurable latency and error mix.

Where Do Test Cards Come From?​

A test card number is issued by your processor, gateway or network for use in its sandbox only. It is mapped to an outcome (approved, declined for insufficient funds, authentication required and so on), and it does not work anywhere else. Do not look for "valid" numbers elsewhere and never use a real card in a test environment.

Use the vendor's own pages:

  • Stripe: Testing, with a generic Visa success card, cards for specific decline codes, and cards for disputes.
  • Adyen: Test card numbers, per scheme and scenario.
  • Mastercard and Visa publish test data inside their developer sandboxes and per product, for example the Mastercard Developers and Visa Developer portals. The Visa sandbox is not connected to the live network.
No card numbers in your repository

This guide prints no card numbers, not even published test numbers, and your tests should not hard-code them either. Keep them in a test-data file that references the vendor's page, load them from configuration, and make secret scanning and PAN-detection tools run over the repository. A real PAN pasted into a fixture is a compliance problem. See Sensitive Data Handling.

How Do You Simulate Chargebacks?​

Disputes arrive days or weeks after a sale, so you cannot wait for them naturally. Use the vendors' simulation tools and then build your own.

Vendor simulation (check each page for current behavior):

  • Stripe documents dispute test cards for several scenarios, for example a fraudulent dispute, product not received, an inquiry, an early fraud warning and multiple disputes, plus test evidence values winning_evidence and losing_evidence that decide the outcome when you submit evidence. See Stripe testing.
  • Adyen documents setting holderName in a test payment to a keyword such as Chargeback, Chargeback:10.4 (with a reason code), Chargeback Reversed or Second Chargeback. The payment must be captured, then moves through settled to chargeback, which can take up to 24 hours, and a NOTIFICATION_OF_CHARGEBACK webhook is sent. Not every dispute type can be simulated. See Adyen: test applicable dispute reasons.

Your own dispute simulator. Vendor tools only cover what the vendor supports and are slow. Build an internal service, available in test environments only, that:

  1. Accepts a command: payment id, reason code, amount, which stage to emit (opened, evidence requested, won, lost, reversed).
  2. Emits a webhook shaped exactly like your processor's payload, signed with the test secret, to your real webhook endpoint.
  3. Lets the test advance time, for example past the evidence due date.

That exercises the whole path: webhook verification, the dispute state machine, the ledger entries for the disputed amount, evidence deadlines stored per dispute, and the merchant balance impact. Deadlines come from the network and processor and are stored per dispute; see Dispute Lifecycle.

How Do You Inject Failures?​

Success paths are easy. Build the fake processor and your queue test harness so each of these can be triggered on demand:

FailureWhat to assert
Processor timeout on authorizeThe payment moves to the explicit unknown state. A resolver queries the processor or sends a reversal. It never re-authorizes blindly. See Idempotency and the idempotency post
Processor returns success after your timeoutLate response reconciles the payment, with no duplicate ledger entry
Duplicate webhookSecond delivery is deduplicated on event id and changes nothing
Out-of-order webhooksA "captured" event before "authorized" does not corrupt state; the handler fetches current state or parks the event
Partial outbox failureThe business change committed, the relay crashes before publishing: the event is still published after restart, possibly twice, and consumers cope. See Event-Driven Architecture
Consumer crash mid-messageMessage redelivered, effect applied once
Late or missing settlement fileAlert fires, dependent jobs hold, the late file is processed once when it arrives
ACH return after payout paidPayout moves to returned, ledger reverses, merchant balance and recovery logic react. See Payouts
Database failover mid-transactionNo half-posted entry; retry is safe

Each test should also assert the telemetry: the unknown-outcome counter incremented, the alert condition became true. That checks the signals defined in Observability.

How Do You Test Concurrency?​

Concurrency bugs pass every sequential test. Two cases deserve dedicated tests against a real database:

  1. Parallel identical requests with one idempotency key. Exactly one must execute the side effect; the others must replay the stored response or receive a conflict while the first is in progress.
  2. Parallel payouts against one balance. If two payouts of 70 are requested against a balance of 100, at most one may succeed. See Balances for guards.
import { randomUUID } from 'node:crypto';
import { Test } from '@nestjs/testing';
import { getDataSourceToken } from '@nestjs/typeorm';
import { PaymentsService } from './payments.service';
import { CreatePaymentDto } from './dto/create-payment.dto';
import { FakeProcessor } from '../testing/fake-processor';
import { testDataSource } from '../testing/test-data-source'; // real Postgres container

describe('Idempotent payment creation under concurrency', () => {
let service: PaymentsService;
const processor = new FakeProcessor({ latencyMs: 50 });

beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
providers: [
PaymentsService,
{ provide: getDataSourceToken(), useValue: testDataSource },
{ provide: 'PROCESSOR', useValue: processor },
],
}).compile();
service = moduleRef.get(PaymentsService);
});

// Each test uses its own key so the tests do not depend on each other or on shared state.
const uniqueKey = (label: string) => `key-${label}-${randomUUID()}`;

beforeEach(() => processor.reset());

it('runs the processor call once for 20 parallel requests with one key', async () => {
const dto: CreatePaymentDto = { amount: 1500, currency: 'USD', paymentMethod: 'pm_tok_[redacted]' };
const key = uniqueKey('parallel');

const results = await Promise.allSettled(
Array.from({ length: 20 }, () => service.create(dto, key)),
);

expect(processor.authorizeCalls).toBe(1); // side effect once
const ids = new Set(
results.flatMap((r) => (r.status === 'fulfilled' ? [r.value.id] : [])),
);
expect(ids.size).toBe(1); // everyone sees the same payment
// Rejections are allowed only as "in progress" conflicts, never other errors.
for (const r of results) {
if (r.status === 'rejected') expect(r.reason.getStatus()).toBe(409);
}
});

it('rejects the same key with different parameters', async () => {
const key = uniqueKey('mismatch');
await service.create({ amount: 1500, currency: 'USD', paymentMethod: 'pm_tok_[redacted]' }, key);

const err = await service
.create({ amount: 9999, currency: 'USD', paymentMethod: 'pm_tok_[redacted]' }, key)
.catch((e) => e);
expect(err.getStatus()).toBe(422); // same accessor as above
});
});

The unique constraint on the key is what makes the first test pass reliably; a test that passes only because the machine is slow proves nothing. Run it many times, and in CI with parallelism raised.

How Do You Test Reconciliation with Synthetic Files?​

Generate settlement and funding files from your own fixtures: take the payments your test run created, produce a file in the processor's format with matching amounts, fees and identifiers, then deliberately corrupt it: a missing line, an extra line, an amount off by one minor unit, a duplicate record, a wrong trailer count, a file delivered twice. Assert each produces the expected break type and that clean files produce none. The formats and ingestion rules are in Settlement Files, and break taxonomy is in Reconciliation. Keep the generator beside the parser so format changes break the test.

What About Certification?​

Before going live you will normally run certification: the acquirer or processor supplies a script of test cases (authorizations, reversals, partial captures, refunds, error handling) and checks the results. Network and acquirer certification scripts are supplied by your acquirer or processor and are not public. Ask early, because scheduling can take longer than the build, and design your test harness so that the same scenarios can be replayed from your automated suite.

How Should You Manage Test Data?​

  • Synthetic by default. Generate names, addresses, emails, business details and identity data with a generator. Never use real people.
  • No production copies in lower environments. If you cannot avoid one, mask irreversibly before it leaves production and have security leadership approve the process.
  • Bank accounts, tax ids and dates of birth in tests must be obviously fake values that your own validators accept; confirm with the vendor's sandbox documentation which values it accepts.
  • Environment isolation. Separate keys, databases and webhook secrets per environment. Test keys must be unable to reach live services.
  • Cleanup. Reset state between tests with transactions or truncation so tests do not depend on order.

How Do You Design a Sandbox for Your Own Platform Customers?​

If you are a PayFac, your customers (platforms and sub-merchants) need a sandbox as much as you needed the processor's. Design it as a product:

FeatureDesign
Separate test and liveDistinct API keys with visible prefixes, distinct data stores, no way to cross over
Deterministic outcomes"Magic values", such as special amounts or token ids that always decline, require authentication or time out, documented in a public table
Webhook triggersAn endpoint or dashboard button that emits any event type to the customer's endpoint
Dispute and return simulationCommands that open a dispute, win or lose it, or return a payout
Time travelA test clock that advances payout schedules, reserve releases and dispute deadlines without waiting days
RealismSame validation, same error format, same state machines as live; fake only the money rails
SafetyRate limits. In test mode accept only your documented magic tokens or test card list and reject every other Luhn-valid number. Prefer tokenized or hosted-field input so the sandbox never receives card data

Test mode must run the same code paths as live, with only the processor adapter swapped for your fake. Otherwise customers certify against behavior that does not exist in production.

Self-Assessment Questions​

1. Why test against your own simulator for load rather than the processor sandbox? Sandboxes are rate-limited and not intended for load, and results would measure the sandbox, not your platform.

2. Which assertion shows that a timeout was handled correctly? The payment is in the unknown state and is resolved by query or reversal, with a single ledger effect. A second authorization is a failure.

3. Why must the idempotency concurrency test use a real database? The guarantee comes from a unique constraint and transaction isolation, which in-memory mocks do not reproduce.

References​

Share: