testing/synctest
Use `testing/synctest` for deterministic tests of concurrent code that otherwise depend on timing or scheduler luck.
Canonical guidance
- use
testing/synctestfor deterministic concurrent tests - prefer fake time and controlled scheduling over flaky sleeps
- keep the bubble scope obvious
Use when
- retry loops with timers
- background goroutines that need deterministic advancement
- concurrency code that flakes under scheduler timing
Avoid
- sleeping real milliseconds in tests that only need synchronization
- wrapping every concurrency test in synctest when plain channels are enough
- unclear bubble boundaries
Preferred pattern
synctest.Run(func() {
// run concurrent code inside a deterministic bubble
})
Anti-pattern
- adding
time.Sleep(50 * time.Millisecond)until a flaky concurrent test “usually” passes
Explanation: This anti-pattern is tempting because it is easy, but it replaces correctness with timing luck.
Why
- deterministic concurrency tests are faster and more trustworthy than scheduler-dependent sleeps
Related pages
Sources
- testing/synctest package - Go Team