表格驅動測試
最後更新
本頁說明如何把多組輸入與預期結果整理成一張「測試表」,再搭配
t.Run 子測試與 t.Parallel 平行執行。為什麼用表格
同一個函式通常要測很多組輸入:一般值、邊界值、空值、錯誤值。如果每組都寫一個
TestXxx,會出現大量重複的程式碼。表格驅動測試(table-driven test)的做法是:把「輸入」和「預期輸出」列成一張表(通常是結構體切片),再用一個
for 迴圈逐列檢查。就像考卷的對答案表,新增一題只要多寫一列。基本的測試寫法(
_test.go、TestXxx、t.Errorf)見單元測試。測試表與子測試
測試表
測試表通常宣告成匿名結構體的切片(切片、結構體),每個欄位代表一個輸入或預期值。迴圈內用
t.Errorf,讓一列失敗時其他列仍會繼續檢查。被測程式
grade.go(故意埋了 bug:及格線寫成 score > 60):- package grade
- func Grade(score int) string {
- switch {
- case score >= 90:
- return "A"
- case score >= 80:
- return "B"
- case score > 60:
- return "C"
- default:
- return "F"
- }
- }
測試檔
grade_test.go:- package grade
- import "testing"
- func TestGrade(t *testing.T) {
- tests := []struct {
- score int
- want string
- }{
- {95, "A"},
- {90, "A"},
- {85, "B"},
- {70, "C"},
- {60, "C"},
- {10, "F"},
- }
- for _, tt := range tests {
- if got := Grade(tt.score); got != tt.want {
- t.Errorf("Grade(%d) = %q, want %q", tt.score, got, tt.want)
- }
- }
- }
執行(
go.mod 的 module 為 example.com/grade):- go test
輸出:
- --- FAIL: TestGrade (0.00s)
- grade_test.go:19: Grade(60) = "F", want "C"
- FAIL
- exit status 1
- FAIL example.com/grade 0.233s
表格把邊界值 60 測出了問題。最後的耗時數字因機器而異。
t.Run 子測試
t.Run(name, f) 在目前測試底下建立一個子測試(subtest),每個子測試有自己的名稱與結果。好處有三:- 輸出會列出是哪一列失敗,不必在訊息裡自己標示
- 子測試裡用
t.Fatal只會結束該列,其他列照常執行 - 可以用
-run 父測試/子測試只跑某幾列
簽名:
- func (t *T) Run(name string, f func(t *T)) bool
測試檔
grade_test.go(被測程式同上):- package grade
- import "testing"
- func TestGrade(t *testing.T) {
- tests := []struct {
- name string
- score int
- want string
- }{
- {"top", 95, "A"},
- {"boundary A", 90, "A"},
- {"middle B", 85, "B"},
- {"boundary C", 60, "C"},
- {"fail", 10, "F"},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := Grade(tt.score); got != tt.want {
- t.Fatalf("Grade(%d) = %q, want %q", tt.score, got, tt.want)
- }
- })
- }
- }
執行:
- go test -v
- go test -v -run 'TestGrade/boundary'
輸出:
- === RUN TestGrade
- === RUN TestGrade/top
- === RUN TestGrade/boundary_A
- === RUN TestGrade/middle_B
- === RUN TestGrade/boundary_C
- grade_test.go:20: Grade(60) = "F", want "C"
- === RUN TestGrade/fail
- --- FAIL: TestGrade (0.00s)
- --- PASS: TestGrade/top (0.00s)
- --- PASS: TestGrade/boundary_A (0.00s)
- --- PASS: TestGrade/middle_B (0.00s)
- --- FAIL: TestGrade/boundary_C (0.00s)
- --- PASS: TestGrade/fail (0.00s)
- FAIL
- exit status 1
- FAIL example.com/grade 0.227s
- === RUN TestGrade
- === RUN TestGrade/boundary_A
- === RUN TestGrade/boundary_C
- grade_test.go:20: Grade(60) = "F", want "C"
- --- FAIL: TestGrade (0.00s)
- --- PASS: TestGrade/boundary_A (0.00s)
- --- FAIL: TestGrade/boundary_C (0.00s)
- FAIL
- exit status 1
- FAIL example.com/grade 0.052s
子測試名稱中的空白會被換成底線,所以
boundary A 顯示為 boundary_A。-run 的參數以 / 分層,每一層各自是正規表示式:TestGrade/boundary 只跑名稱含 boundary 的子測試。注意:Go 1.22 起
for 迴圈每次迭代都有新的 tt 變數,閉包直接使用 tt 是安全的;舊版教學中常見的 tt := tt 已經不需要。t.Parallel 平行執行
t.Parallel() 宣告這個測試可以和其他平行測試同時執行。子測試呼叫它之後會先暫停(PAUSE),等父測試的迴圈跑完,所有平行子測試再一起繼續(CONT)。適合彼此獨立、會等待 I/O 或耗時較久的測試。同時執行的數量上限由
-parallel 旗標控制,預設等於 GOMAXPROCS。被測程式
fetch.go(用 time.Sleep 模擬耗時 300 毫秒的工作):- package fetch
- import (
- "strings"
- "time"
- )
- func Slow(s string) string {
- time.Sleep(300 * time.Millisecond)
- return strings.ToUpper(s)
- }
測試檔
fetch_test.go:- package fetch
- import "testing"
- func TestSlow(t *testing.T) {
- tests := []struct {
- name string
- in string
- want string
- }{
- {"a", "a", "A"},
- {"b", "b", "B"},
- {"c", "c", "C"},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- t.Parallel()
- if got := Slow(tt.in); got != tt.want {
- t.Errorf("Slow(%q) = %q, want %q", tt.in, got, tt.want)
- }
- })
- }
- }
執行(
go.mod 的 module 為 example.com/fetch):- go test -v -count=1
- go test -count=1 -parallel 1
輸出:
- === RUN TestSlow
- === RUN TestSlow/a
- === PAUSE TestSlow/a
- === RUN TestSlow/b
- === PAUSE TestSlow/b
- === RUN TestSlow/c
- === PAUSE TestSlow/c
- === CONT TestSlow/a
- === CONT TestSlow/b
- === CONT TestSlow/c
- --- PASS: TestSlow (0.00s)
- --- PASS: TestSlow/c (0.30s)
- --- PASS: TestSlow/b (0.30s)
- --- PASS: TestSlow/a (0.30s)
- PASS
- ok example.com/fetch 0.353s
- PASS
- ok example.com/fetch 0.953s
三個各需 0.3 秒的子測試,平行時總共約 0.35 秒;用
-parallel 1 限制一次只跑一個,就變成約 0.95 秒。耗時數字因機器而異;平行子測試的 CONT 與 PASS 行的先後順序每次也可能不同。注意:平行測試會同時執行,若共用同一個變數、檔案或全域狀態,就會產生競態條件。只對彼此獨立的測試呼叫
t.Parallel();呼叫了 t.Parallel() 的測試也不能再用 t.Setenv 或 t.Chdir,否則會 panic。重點整理
- 測試表用結構體切片列出輸入與預期值,新增案例只要加一列
t.Run(name, f)為每一列建立子測試,失敗時能直接看出是哪一列-run 父測試/子測試可以只跑指定的子測試,名稱中的空白會變成底線t.Parallel()讓彼此獨立的子測試同時執行,數量上限由-parallel控制- Go 1.22 起不必再寫
tt := tt