Skip to content
Latchkey

Go "-shuffle" Test Failures - Fix Order-Dependent Tests in CI

go test -shuffle=on randomizes test execution order, and a test that depends on running after another now fails. The tests share package-level or global state, so they only pass in their original source order.

What this error means

Tests pass without shuffling but fail under -shuffle=on, and the failure changes with the seed. The output prints the seed so you can reproduce it. The root cause is hidden coupling through shared state, not a flaky environment.

go test output
-test.shuffle 1700000000000000000
--- FAIL: TestUsesGlobal (0.00s)
    global_test.go:30: cache not initialized; expected seeded value
FAIL	github.com/org/app/internal/cache	0.008s

Common causes

Tests share package-level or global state

One test sets up state (a global, a package var, a singleton) that another relies on. In source order it works; shuffled, the dependent test runs first and fails.

Missing per-test setup/teardown

Without resetting state between tests, leftover values from a prior test leak into the next, making outcomes order-sensitive.

How to fix it

Reproduce with the printed seed

Re-run with the exact seed to get the same order and debug it deterministically.

Terminal
go test -shuffle=1700000000000000000 -v ./internal/cache

Make each test set up its own state

  1. Initialize the state each test needs inside that test (or a helper), not in another test.
  2. Reset shared state with t.Cleanup so nothing leaks between tests.
  3. Prefer local instances over package-level globals in tests.

Keep shuffle on in CI to catch regressions

.github/workflows/ci.yml
go test -shuffle=on ./...

How to prevent it

  • Avoid shared package-level state between tests; isolate per test.
  • Use t.Cleanup to reset any state you must share.
  • Run go test -shuffle=on ./... in CI.

Frequently asked questions

What causes ""-shuffle" exposes ordering bugs"?
One test sets up state (a global, a package var, a singleton) that another relies on. In source order it works; shuffled, the dependent test runs first and fails.
How do I fix "-shuffle" exposes ordering bugs?
Re-run with the exact seed to get the same order and debug it deterministically.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card