Every few weeks a test fails in CI and passes on your laptop. Half the time the culprit is the clock. A test that calls time.Now() deep inside the code under test is really asserting something about the exact instant the test ran, and that instant is different on a loaded build machine.
The fix is boring and permanent: stop reading the global clock. Pass a clock in.
type Clock interface {
Now() time.Time
}
type realClock struct{}
func (realClock) Now() time.Time { return time.Now() }
// In tests, a clock you control:
type fixedClock struct{ t time.Time }
func (c fixedClock) Now() time.Time { return c.t }
Now the thing that needs the time takes a Clock, and production wires in realClock{} while the test wires in a fixed instant. The assertion becomes exact instead of approximate.
func TestTokenExpires(t *testing.T) {
start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
tok := NewToken(fixedClock{start}, time.Hour)
if tok.Valid(fixedClock{start.Add(59 * time.Minute)}) == false {
t.Fatal("token should still be valid at 59m")
}
if tok.Valid(fixedClock{start.Add(61 * time.Minute)}) {
t.Fatal("token should be expired at 61m")
}
}
No sleeps, no tolerances, no time.Now().Add(-x) dance. The same pattern works for rate limiters, caches, retry backoff and anything with a TTL. The rule I follow: if the behaviour depends on time, the time is an input, not an ambient fact.
What about tickers?
For code driven by time.Ticker, hide the ticker behind the same interface and have the fake emit ticks on demand. Your test advances time explicitly, so a one-hour schedule runs in microseconds and never races.