Testing Strategy
- Design a test portfolio for a Go microservice and justify its shape (pyramid, trophy or honeycomb)
- Choose the right test double — fake, stub, spy or mock — and keep fakes honest with contract tests
- Write table-driven, testcontainers-backed and property-based tests for payment and ledger code
- Test asynchronous, event-driven flows without sleeps, including duplicate and out-of-order delivery
- Diagnose and eliminate flaky tests, and explain consumer-driven contract testing (Pact)
TL;DR
- A test strategy is a portfolio: fast unit tests for domain rules, service-level integration tests with a real database, contract tests between services, and a handful of end-to-end journeys.
- For Go microservices, the most valuable layer is usually the service tested through its API with a real Postgres (testcontainers) — the honeycomb, not a pyramid of mocks.
- Prefer fakes for stateful dependencies (repositories) and verify them with shared contract tests; use spies/mocks only for the outbound interactions that matter (the PSP is charged exactly once).
- Money and ledger code deserves property-based tests: parts sum to the total, journal entries balance, transfers conserve money.
- Async flows: test the handler as a function, deliver every message twice, deliver out of order, and replace
time.Sleepwith polling or a fake clock. - Coverage measures execution, not verification. Mutation testing shows whether your assertions would catch a bug.
- Flaky tests are bugs — often real race conditions. Fix the cause (clock, ordering, shared state), do not just retry.
Why it matters
In payments, a defect is not a bad user experience; it is money moved incorrectly — a double charge, a refund above the captured amount, an unbalanced ledger entry. Regulators and auditors (PCI DSS, SOX-style change controls in banks) expect evidence that changes are tested. And e-commerce teams that ship many times a day during a sale season can only do so if the test suite is fast, trustworthy and green.
A good strategy also shapes design: code that is hard to test (I/O tangled with rules, global state, time.Now() everywhere) is usually hard to change. The architect's job is to set the portfolio and the standards — what each layer is for, what "done" means for tests, and how long CI may take.
Core concepts
Pyramid, trophy and honeycomb
- Pyramid (Mike Cohn): many fast unit tests, fewer service tests, very few UI tests. Sound economics, but in microservices "unit" often degenerates into mock-heavy tests that mirror the implementation.
- Trophy (Kent C. Dodds, from the frontend world): static analysis as the base, integration tests as the bulk — "the more your tests resemble the way your software is used, the more confidence they can give you."
- Honeycomb (Spotify engineering): for microservices, focus on testing each service through its API with its real dependencies, with few implementation-detail tests and few cross-service integrated tests.
A pragmatic Go-service portfolio: golangci-lint and go vet as the base; pure unit tests for domain logic (pricing, fees, state machines, money); the bulk as service-level tests through HTTP/gRPC handlers with a real database; contract tests for every API and event you expose or consume; a few E2E journeys in staging.
Test types
| Type | Scope | Real dependencies | Speed (rough) | Catches | Misses |
|---|---|---|---|---|---|
| Unit | Function, type, package | None | Microseconds to milliseconds | Logic, edge cases, rounding | Wiring, SQL, serialization |
| Service / integration | One service through its API | Database, cache, maybe broker | Tens to hundreds of ms per test; seconds to start containers | SQL, migrations, transactions, handlers, config | Other services' behavior |
| Contract | Interface between two services | Neither, or the provider only | Fast | Breaking API or event changes | Business correctness of either side |
| End-to-end | Whole journey across services | Everything (staging) | Seconds to minutes | Deployment, config, cross-service flows | Edge cases (too slow to enumerate) |
Table-driven tests
The Go idiom for exercising many cases of one rule. Each row is a case; t.Run gives each a name you can run alone (go test -run 'CheckRefundable/window_closed').
func TestPayment_CheckRefundable(t *testing.T) {
now := time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC)
vnd := func(v int64) money.Money { return money.MustNew(v, "VND") }
tests := []struct {
name string
payment Payment
amount money.Money
wantErr error
}{
{"partial refund", captured(vnd(500_000), vnd(0), now.AddDate(0, 0, -10)), vnd(200_000), nil},
{"exact full refund", captured(vnd(500_000), vnd(0), now.AddDate(0, 0, -10)), vnd(500_000), nil},
{"exceeds remaining", captured(vnd(500_000), vnd(400_000), now.AddDate(0, 0, -10)), vnd(200_000), ErrRefundExceedsCapture},
{"window closed", captured(vnd(500_000), vnd(0), now.AddDate(0, 0, -181)), vnd(1), ErrRefundWindowClosed},
{"not captured", Payment{Status: StatusAuthorized}, vnd(1), ErrNotCaptured},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
err := tt.payment.CheckRefundable(tt.amount, now)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("CheckRefundable() error = %v, want %v", err, tt.wantErr)
}
})
}
}
Notes: since Go 1.22 the loop variable is per-iteration, so the old tt := tt copy is no longer needed with t.Parallel(). Inject now instead of calling time.Now(). For struct comparisons, github.com/google/go-cmp/cmp.Diff gives readable failure output. Boundary rows — "exact full refund", "window closed by one day" — are where real bugs live.
Test doubles: fakes vs mocks
Gerard Meszaros' taxonomy (xUnit Test Patterns) gives precise names:
| Double | What it does | Good for |
|---|---|---|
| Dummy | Fills a parameter, never used | Satisfying a constructor |
| Stub | Returns canned answers | Queries: "the FX rate service returns 25,000" |
| Spy | Records calls for later assertions | Outbound commands: "PSP charged once with key X" |
| Mock | Pre-programmed expectations, fails on unexpected calls | Strict protocol checks (rarely needed) |
| Fake | Working lightweight implementation | Stateful dependencies: in-memory repository, in-memory broker |
The two schools: classical (Detroit) tests use real objects and fakes and assert on resulting state; mockist (London) tests isolate each unit and assert on interactions. In Go services, a classical bias works best: mock-heavy tests that assert "Save was called with these arguments" break on every refactor while missing real bugs (SQL, transactions).
// Fake: a working in-memory repository with the same contract as Postgres.
// It is kept honest by running the shared contract suite against both.
type FakeOrderRepo struct {
mu sync.Mutex
orders map[order.ID]order.Order
}
func NewFakeOrderRepo() *FakeOrderRepo {
return &FakeOrderRepo{orders: make(map[order.ID]order.Order)}
}
func (r *FakeOrderRepo) Get(_ context.Context, id order.ID) (*order.Order, error) {
r.mu.Lock()
defer r.mu.Unlock()
o, ok := r.orders[id]
if !ok {
return nil, order.ErrNotFound
}
return &o, nil // a copy: callers must not mutate stored state
}
func (r *FakeOrderRepo) Save(_ context.Context, o *order.Order) error {
r.mu.Lock()
defer r.mu.Unlock()
if cur, ok := r.orders[o.ID]; ok && cur.Version != o.Version {
return order.ErrConflict // same optimistic-lock semantics as Postgres
}
o.Version++
r.orders[o.ID] = *o
return nil
}
// Spy: records calls so the test can assert the one interaction that
// matters — the PSP is charged exactly once, with the idempotency key.
type spyProvider struct {
mu sync.Mutex
calls []payment.ChargeRequest
resp payment.ChargeResult
err error
}
func (s *spyProvider) Charge(_ context.Context, req payment.ChargeRequest) (payment.ChargeResult, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.calls = append(s.calls, req)
return s.resp, s.err
}
func TestPlaceOrder_RetryChargesOnce(t *testing.T) {
psp := &spyProvider{resp: payment.ChargeResult{Ref: "ch_1", Status: payment.Approved}}
uc := newPlaceOrder(t, withProvider(psp), withOrders(NewFakeOrderRepo()))
cmd := aPlaceOrderCmd().WithIdempotencyKey("idem-123").Build()
first, err := uc.Handle(context.Background(), cmd)
if err != nil {
t.Fatal(err)
}
second, err := uc.Handle(context.Background(), cmd) // client retry after a timeout
if err != nil {
t.Fatal(err)
}
if first.OrderID != second.OrderID {
t.Errorf("retry created a second order: %s vs %s", first.OrderID, second.OrderID)
}
if len(psp.calls) != 1 {
t.Fatalf("PSP charged %d times, want 1", len(psp.calls))
}
if got := psp.calls[0].IdempotencyKey; got != "idem-123" {
t.Errorf("idempotency key = %q, want idem-123", got)
}
}
The danger with fakes is drift: the fake returns nil, nil where Postgres returns ErrNotFound, or it never produces a conflict. A contract test suite run against both implementations prevents that (see SOLID in Go). Mocking libraries (gomock, testify/mock) are fine for narrow interfaces at boundaries; a generated mock for a 15-method interface is a design smell, not a testing problem.
Integration tests with testcontainers
Mocking SQL tests nothing that matters: the bugs are in the query, the index, the transaction isolation, the migration. Run a real Postgres in Docker per test package with testcontainers-go:
//go:build integration
package store_test
var testDSN string
func TestMain(m *testing.M) {
ctx := context.Background()
ctr, err := postgres.Run(ctx, "postgres:16-alpine",
postgres.WithDatabase("payments"),
postgres.WithUsername("test"),
postgres.WithPassword("test"),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2).
WithStartupTimeout(60*time.Second)),
)
if err != nil {
log.Fatalf("start postgres: %v", err)
}
dsn, err := ctr.ConnectionString(ctx, "sslmode=disable")
if err != nil {
log.Fatalf("connection string: %v", err)
}
if err := migrate(dsn); err != nil { // the same migrations production runs
log.Fatalf("migrate: %v", err)
}
testDSN = dsn
code := m.Run()
_ = ctr.Terminate(ctx)
os.Exit(code)
}
Isolation between tests is the main design decision:
| Strategy | How | Trade-off |
|---|---|---|
| Transaction per test, rolled back | Wrap each test in a tx | Fast, but fails if the code under test manages its own transactions |
| Truncate tables between tests | TRUNCATE ... CASCADE in t.Cleanup | Simple; tests in a package cannot run in parallel |
| Database per test from a template | CREATE DATABASE t_123 TEMPLATE migrated | Parallel-safe and reasonably fast in Postgres |
| Unique data per test | Random IDs, tenant per test | Parallel-safe; assertions must filter by test data |
Practical notes: keep integration tests behind a build tag or testing.Short() so the inner loop stays fast; container start-up is usually a few seconds (varies by machine and image), so start once per package, not per test; pin image versions to what production runs. The same approach works for Redis, Kafka (or Redpanda) and LocalStack.
Contract tests (Pact)
Between services, the question is "will my change break my consumers?". End-to-end tests answer it slowly and flakily. Consumer-driven contract testing answers it cheaply: the consumer records the requests it makes and the responses it relies on; the provider replays them against its real implementation in its own CI.
Contracts cover only what the consumer uses — if checkout ignores payment.fee_breakdown, payments can change that field freely. For events, the equivalent is message pacts or, more commonly, a schema registry with compatibility rules (for example Avro or Protobuf with backward compatibility enforced in CI). Contract tests do not check business correctness; each side still needs its own tests. See API Design for evolving contracts.
End-to-end tests
Keep a small set of critical journeys — browse, add to cart, checkout with a test card, refund — running in staging after every deploy, and the same journeys as synthetic transactions in production with test merchant accounts or test cards, alerting through your observability stack. Anything you can test lower in the portfolio, test there: E2E tests are the slowest, flakiest and hardest to debug.
Property-based testing for money and ledgers
Example-based tests check the cases you thought of. Property-based tests generate hundreds of inputs and check an invariant that must always hold — and when one fails, the library shrinks it to a minimal counterexample. Money and ledger code is full of such invariants:
- Allocation: the parts always sum to the total, and no part is negative.
- Journal entries: debits equal credits per currency.
- Transfers: the total across accounts is conserved; no account goes below its limit.
- Round trips:
Parse(Format(m)) == m; event replay rebuilds the same balance.
import "pgregory.net/rapid"
func TestAllocate_PartsSumToTotal(t *testing.T) {
rapid.Check(t, func(t *rapid.T) {
amount := rapid.Int64Range(0, 100_000_000_000).Draw(t, "amount")
ratios := rapid.SliceOfN(rapid.Int64Range(1, 1000), 1, 20).Draw(t, "ratios")
parts, err := money.MustNew(amount, "USD").Allocate(ratios...)
if err != nil {
t.Fatalf("allocate: %v", err)
}
var sum int64
for _, p := range parts {
if p.Minor() < 0 {
t.Fatalf("negative part %v", p)
}
sum += p.Minor()
}
if sum != amount {
t.Fatalf("parts sum to %d, want %d", sum, amount)
}
})
}
// Model-based: a random sequence of transfers must never create or destroy money.
func TestLedger_ConservesMoney(t *testing.T) {
rapid.Check(t, func(t *rapid.T) {
l := ledger.NewInMemory()
accounts := []ledger.AccountID{"A", "B", "C"}
for _, a := range accounts {
l.Open(a, money.MustNew(10_000, "VND"))
}
ops := rapid.IntRange(1, 50).Draw(t, "ops")
for range ops {
from := rapid.SampledFrom(accounts).Draw(t, "from")
to := rapid.SampledFrom(accounts).Draw(t, "to")
amt := rapid.Int64Range(1, 20_000).Draw(t, "amount")
err := l.Transfer(from, to, money.MustNew(amt, "VND"))
if err != nil && !errors.Is(err, ledger.ErrInsufficientFunds) && !errors.Is(err, ledger.ErrSameAccount) {
t.Fatalf("unexpected error: %v", err)
}
}
var total int64
for _, a := range accounts {
bal := l.Balance(a)
if bal.Minor() < 0 {
t.Fatalf("account %s went negative: %v", a, bal)
}
total += bal.Minor()
}
if total != 30_000 {
t.Fatalf("money created or destroyed: total = %d, want 30000", total)
}
})
}
Go's built-in fuzzing (go test -fuzz, since Go 1.18) complements this for parsers — amount strings, webhook payloads, ISO 8583 or settlement-file readers — where the property is "never panic, and round-trip correctly":
func FuzzParseAmount(f *testing.F) {
for _, seed := range []string{"0", "19.99", "1000000", "-5.00", "1e3", " 12.5", "0.001"} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, s string) {
m, err := money.Parse(s, "USD")
if err != nil {
return // rejecting bad input is fine; panicking or mis-parsing is not
}
back, err := money.Parse(m.DecimalString(), "USD")
if err != nil || back != m {
t.Fatalf("round trip %q -> %v -> %v (err %v)", s, m, back, err)
}
})
}
The ledger invariants themselves are discussed in Double-Entry Ledger Design.
Mutation testing
Coverage tells you which lines ran, not whether any assertion would notice if they were wrong. Mutation testing changes the code in small ways — > to >=, + to -, delete a statement, negate a condition — and reruns the tests. A mutant that survives (tests still pass) marks a gap.
Example: mutate the refund check from GreaterThan to GreaterThanOrEqual. If no test refunds exactly the remaining amount, the mutant survives — and you have discovered that "full refund" is untested, which is precisely the kind of boundary that breaks in production. Go tools such as gremlins and go-mutesting exist; runs are slow (the suite runs once per mutant), so teams typically run them nightly or on demand for critical packages (money, ledger, pricing) rather than on every PR.
Testing async and event-driven flows
Event-driven code fails in ways synchronous code does not: duplicates, reordering, partial failure between steps, and timing. Test each explicitly:
- Test the handler as a function. Call
Handle(ctx, evt)directly and assert resulting state and emitted events; no broker needed for business logic. - Deliver everything twice. Brokers are at-least-once; the second delivery must have no additional effect.
- Deliver out of order.
PaymentCapturedbeforeOrderCreatedmust be retried, parked or handled — not crash or silently drop. - Assert the outbox, not the broker. The unit of work writes state and the outbox row atomically; test the relay separately (see Transactional Outbox & CDC).
- No
time.Sleepin assertions. Poll with a deadline, or control time: inject a clock, and on Go 1.25+ considertesting/synctest, which runs goroutines in an isolated bubble with a fake clock. - A few broker-level tests with testcontainers (Kafka or Redpanda) for serialization, headers, partition keys and consumer-group configuration.
func TestPaymentCapturedConsumer_IsIdempotent(t *testing.T) {
repo := NewFakeOrderRepo()
repo.Seed(AnOrder().WithID("ord_1").PendingPayment().Build())
c := NewPaymentCapturedConsumer(repo, fixedClock(t0))
evt := PaymentCaptured{EventID: "evt_1", OrderID: "ord_1", Amount: money.MustNew(250_000, "VND")}
for range 2 { // at-least-once delivery: the same message arrives twice
if err := c.Handle(context.Background(), evt); err != nil {
t.Fatalf("handle: %v", err)
}
}
o := repo.MustGet(t, "ord_1")
if o.Status != order.Paid {
t.Fatalf("status = %s, want PAID", o.Status)
}
if n := len(repo.Outbox()); n != 1 {
t.Fatalf("outbox events = %d, want exactly 1", n)
}
}
// eventually polls cond until it holds or the timeout elapses.
func eventually(t *testing.T, timeout time.Duration, cond func() bool) {
t.Helper()
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if cond() {
return
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("condition not met within %v", timeout)
}
Test data builders
Tests become unreadable when every case constructs a full order with twenty fields. A test data builder provides valid defaults and lets each test state only what matters to it:
type OrderBuilder struct {
id order.ID
status order.Status
lines []order.Line
}
func AnOrder() *OrderBuilder {
return &OrderBuilder{
id: "ord_test_1",
status: order.PendingPayment,
lines: []order.Line{{SKU: "SKU-1", Qty: 1, UnitPrice: money.MustNew(100_000, "VND")}},
}
}
func (b *OrderBuilder) WithID(id order.ID) *OrderBuilder {
b.id = id
return b
}
func (b *OrderBuilder) PendingPayment() *OrderBuilder {
b.status = order.PendingPayment
return b
}
func (b *OrderBuilder) Paid() *OrderBuilder {
b.status = order.Paid
return b
}
func (b *OrderBuilder) WithLine(sku string, qty, unitPriceVND int64) *OrderBuilder {
b.lines = append(b.lines, order.Line{SKU: order.SKU(sku), Qty: qty, UnitPrice: money.MustNew(unitPriceVND, "VND")})
return b
}
// Build goes through the domain constructor and transitions so the result
// always satisfies the aggregate's invariants.
func (b *OrderBuilder) Build() *order.Order {
o := order.MustNew(b.id, slices.Clone(b.lines))
if b.status == order.Paid {
o.MustApply(order.EvPaymentCaptured, time.Unix(0, 0).UTC())
}
return o
}
Then a test reads AnOrder().Paid().WithLine("SKU-2", 3, 50_000).Build() — the relevant detail is visible, the rest is defaulted. Build through domain constructors rather than setting fields, so test data cannot represent impossible states. The object mother (fixtures.PaidOrder()) is the simpler cousin; it works until you need many variations.
Flaky tests
A flaky test passes and fails on the same code. Each flake erodes trust until people re-run CI by reflex — and in concurrent payment code, a "flaky" test is often a real race that will happen in production under load.
| Cause | Symptom | Fix |
|---|---|---|
time.Now() in logic | Fails near midnight, month-end, DST changes | Inject a clock; fixed times in tests |
| Map iteration order | Assertions on slice order fail randomly | Sort before comparing; cmp with sort options |
| Data races | Fails under load or with -race | go test -race; fix the synchronization |
| Shared database state | Fails when run with other tests | Isolation strategy (see above); unique data per test |
| Test order dependence | Fails with -shuffle=on | Remove hidden shared state; t.Cleanup |
time.Sleep for async | Fails on slow CI runners | Poll with deadline; fake clock; testing/synctest |
| Real network or third-party sandboxes | Fails when the sandbox is slow or down | Fakes for unit tests; record/replay for adapters |
| Goroutine leaks | Later tests see stray work | go.uber.org/goleak in TestMain |
| Timezone or locale | Fails on developer laptops, passes in CI | Use UTC explicitly; set TZ in CI |
Operational policy: measure flake rate per test, quarantine a flaky test with an owner and a deadline (not forever), and never paper over flakes with blanket automatic retries.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Pure unit tests | Fastest feedback; precise failures | Miss wiring, SQL, serialization | Domain rules, money math, state machines |
| Service tests with real DB | High confidence; survive refactors | Slower; need Docker in CI | The default bulk of a Go service's suite |
| Mocks / spies | Verify specific interactions | Brittle if overused; couple tests to implementation | Outbound commands that matter (charge once, no e-mail on decline) |
| Fakes + contract tests | Realistic, fast, refactor-friendly | Must be maintained and kept honest | Repositories, brokers, caches |
| Consumer-driven contracts | Catch breaking changes before deploy | Setup and broker overhead; not business correctness | Many services owned by different teams |
| End-to-end tests | Prove real journeys work | Slow, flaky, costly to debug | A handful of critical journeys only |
| Property-based / fuzz | Find inputs you never imagined | Need well-defined invariants; slower | Money, ledgers, parsers, serialization |
| Mutation testing | Measures assertion quality | Very slow; noisy equivalent mutants | Critical packages, periodically |
In practice
A CI pipeline that reflects the portfolio — fast checks first, expensive ones later, each stage a gate:
# Everyday
go test -race -shuffle=on -count=1 ./...
# Integration tests behind a build tag
go test -tags=integration -race ./...
# Hunt a suspected flake
go test -run 'TestPlaceOrder_RetryChargesOnce' -count=500 -race ./internal/checkout
# Fuzz a parser for a minute
go test -fuzz=FuzzParseAmount -fuzztime=60s ./internal/money
# Coverage across packages (as a signal, not a target)
go test -coverpkg=./... -coverprofile=cover.out ./... && go tool cover -func=cover.out
Guidance that holds up in real teams:
- Set a time budget. For example, the PR pipeline should stay under roughly 10–15 minutes; when it creeps up, profile the suite instead of adding parallel runners forever.
- Coverage: watch the trend and the critical packages. A rule like "no PR lowers coverage in
money,ledgerandcheckout" is more useful than a global 80% target that invites assertion-free tests. - Test the adapter against reality occasionally. Record PSP sandbox responses, including errors and timeouts, and replay them in adapter tests; run a live sandbox check nightly.
- Production is part of the strategy. Canary analysis, synthetic transactions, feature flags and reconciliation catch what pre-production tests cannot — reconciliation is the test of last resort for money.
- More Go mechanics (benchmarks,
httptest, golden files) are on Testing & Benchmarking.
Common pitfalls
- Mocking the database. Symptom: green tests, then a production failure from a wrong column, a missing index or a deadlock.
- Mock-mirror tests. Every refactor breaks 40 tests that assert call sequences, so the team stops refactoring.
- Unverified fakes. The fake never returns
ErrConflict, so optimistic-locking bugs reach production. - Sleep-based async tests. CI is slow and still flaky; developers add longer sleeps.
- Retrying flaky tests automatically. A real race in balance updates is hidden until month-end reconciliation finds a mismatch.
- Only happy paths for the PSP. No tests for timeouts, unknown statuses or duplicate webhooks — the exact situations that cause double charges.
- A huge E2E suite. Hour-long pipelines, frequent red builds nobody owns, and deploys batched up to reduce pain — increasing risk.
- Coverage targets as goals. Tests that execute code but assert nothing; mutation testing would reveal them.
Interview angle
- Prompts: "How would you test a payment system?", "How do you test microservices without a giant E2E suite?", "How do you know your tests are good?", "How do you handle flaky tests?"
- A strong answer lays out the portfolio and why: unit tests for money and state machines, property-based tests for invariants, service tests with real Postgres, contract tests between services, a few E2E journeys, and production safety nets (canary, synthetic transactions, reconciliation). It names specific failure modes tested deliberately: idempotent retries, PSP timeouts leading to unknown outcomes, duplicate and out-of-order events, concurrency on balances.
- Expected follow-ups: "Mocks or fakes?", "How do you keep CI fast?", "What does Pact give you that E2E does not?", "How do you test something time-dependent like a payment expiry job?"
- Red flags: "we aim for 100% coverage", "we mock everything", no mention of concurrency or idempotency tests in a payments context, or relying solely on QA in staging.
Self-check
1. Why is the honeycomb often a better fit than the pyramid for Go microservices?
Much of a microservice's risk sits in its integration points — SQL, transactions, serialization, configuration — rather than in complex in-process logic. Testing the service through its API with real dependencies catches those bugs and survives refactors, while a large layer of mock-based "unit" tests mirrors the implementation and misses them. You still keep pure unit tests where there is real logic (money, pricing, state machines).
2. When do you use a fake, a stub, a spy and a mock?
- Fake: stateful dependencies where behavior matters across calls (repositories), kept honest by contract tests.
- Stub: queries with canned answers (an FX rate, a feature flag).
- Spy: outbound commands you must verify happened in a specific way (PSP charged once with the idempotency key).
- Mock with strict expectations: rarely — when the protocol itself is the requirement.
3. Give three properties you would test with property-based tests in a ledger or payment system.
Allocation parts always sum to the original amount with no negative part; every journal entry balances (debits equal credits per currency); any sequence of transfers conserves total money and never takes an account below its limit. Others: parse/format round trips, and replaying events yields the same balance as the live projection.
4. What does mutation testing reveal that coverage does not? Give a payments example.
Whether tests would fail if the code were wrong. Coverage only shows lines executed. Mutating > to >= in a refund-limit check and seeing the suite still pass reveals that no test covers refunding exactly the remaining amount — a boundary that matters to customers and finance.
5. How do you test an event consumer for at-least-once delivery and out-of-order messages?
Call the handler directly with the same event twice and assert a single effect (state changed once, one outbox event). Deliver a dependent event before its predecessor and assert the documented behavior (retry with backoff, park for later, or idempotent no-op) without crashing or dropping it. Use a fake clock or polling instead of sleeps, and keep a few broker-level tests for serialization and keys.
6. Scenario: a test of concurrent wallet withdrawals fails about 1 in 200 runs. The team proposes adding automatic retries in CI. What do you do?
Refuse the blanket retry. Reproduce with go test -race -count=1000 on that test; a 1-in-200 failure in concurrent money code very likely indicates a real race — missing row lock, check-then-act without optimistic locking, or shared state in the test. Fix the cause, add a deterministic regression test if possible, and quarantine only temporarily with an owner and a deadline.
7. What does consumer-driven contract testing guarantee, and what does it not?
It guarantees that the provider still satisfies every interaction its consumers recorded — the requests they send and the response fields they rely on — before either side deploys (can-i-deploy). It does not guarantee business correctness of either service, cover interactions no consumer recorded, or replace each team's own tests.
Exercise
Build a test suite for a small wallet service (top-up, withdraw, transfer, list transactions) backed by Postgres:
- Unit: table-driven tests for withdrawal rules (insufficient funds, daily limit, frozen account, exact-balance withdrawal).
- Property-based: with
rapid, generate random sequences of top-ups, withdrawals and transfers against an in-memory model and assert money conservation and no negative balances. - Integration: testcontainers Postgres, real migrations, database-per-test from a template; include a test firing 50 concurrent withdrawals at one wallet and asserting the final balance and transaction count.
- Contract: a shared
RunWalletRepoContractexecuted against both the in-memory fake and Postgres. - Async: a
TopUpConfirmedconsumer tested with duplicate and out-of-order delivery. - Flake hunt: run the whole suite with
-race -shuffle=on -count=20and fix anything that fails.
Done when: unit and property tests run in under a few seconds without Docker; the concurrency test passes 100 consecutive runs with -race; the fake and Postgres pass the same contract suite; and a deliberately introduced bug (remove the row lock, or change > to >= in the limit check) is caught by at least one test.
Further reading
- Mike Cohn, Succeeding with Agile (2009) — origin of the test pyramid.
- Ham Vocke, "The Practical Test Pyramid" (martinfowler.com, 2018).
- Kent C. Dodds, "The Testing Trophy and Testing Classifications" (blog post).
- André Schaffer, "Testing of Microservices" (Spotify Engineering blog, 2018) — the testing honeycomb.
- Gerard Meszaros, xUnit Test Patterns (2007) — test double taxonomy.
- Steve Freeman and Nat Pryce, Growing Object-Oriented Software, Guided by Tests (2009).
- Vladimir Khorikov, Unit Testing: Principles, Practices, and Patterns (2020) — classical vs London school, what to mock.
- Titus Winters, Tom Manshreck, Hyrum Wright (eds.), Software Engineering at Google (2020) — testing chapters, test doubles, flakiness.
- Go fuzzing documentation
- Go wiki: TableDrivenTests
- Testcontainers for Go
- Pact documentation
pgregory.net/rapid— property-based testing library for Go (source on GitHub: flyingmutant/rapid).
Related
- Testing & Benchmarking — Go testing mechanics, benchmarks,
httptest, golden files. - Code Smells & Refactoring — characterization tests as the refactoring safety net.
- SOLID in Go — small interfaces that make fakes trivial; LSP and contract tests.
- Idempotency & Exactly-Once — the behavior duplicate-delivery tests verify.
- Event-Driven Architecture, CQRS & Event Sourcing — the async flows under test.
- Double-Entry Ledger Design — the invariants property-based tests enforce.
- Reconciliation & Settlement — the production-side safety net for money.
- Cloud-Native, Kubernetes & Deployment Strategies — canaries and progressive delivery.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).