Go synctest:徹底解決並發測試的痛點
Go 語言以 goroutine 和 channel 聞名,併發測試場景卻常常讓人頭痛:sleep 不夠會 fail,sleep 太久拖慢 CI,偶發錯誤難以重現。
Go 1.24 開始,提供了一個令人振奮的實驗性測試新功能:synctest。讓這一切成為過去!!預計將在 8 月釋出的 Go 1.25 正式釋出。
為什麼傳統並發測試這麼難寫?
讓我們看一個常見的例子:假設你要測試一個 goroutine 工作是否如期完成。
func TestWorker(t *testing.T) {
...
ganhua.wang10 min read
1.25 的 synctest 看起來沒有 Run
應該是這樣吧
func TestAfterFunc(t *testing.T) { synctest.Test(t, func(*testing.T) { ctx, cancel := context.WithCancel(context.Background()) called := false context.AfterFunc(ctx, func() { called = true }) synctest.Wait() // 等到所有 goroutine 都卡住 if called { t.Fatal("AfterFunc 在 cancel 前就被呼叫") } cancel() synctest.Wait() // 再等一次 if !called { t.Fatal("AfterFunc 沒有在 cancel 後被呼叫") } }) }