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.
-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.008sCommon 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.
go test -shuffle=1700000000000000000 -v ./internal/cacheMake each test set up its own state
- Initialize the state each test needs inside that test (or a helper), not in another test.
- Reset shared state with
t.Cleanupso nothing leaks between tests. - Prefer local instances over package-level globals in tests.
Keep shuffle on in CI to catch regressions
go test -shuffle=on ./...How to prevent it
- Avoid shared package-level state between tests; isolate per test.
- Use
t.Cleanupto reset any state you must share. - Run
go test -shuffle=on ./...in CI.