單元測試

最後更新


本頁說明如何用 Go 內建的 testing 套件撰寫單元測試,並用 go test 執行。

為什麼要寫單元測試


單元測試(unit test)是一段「自動檢查程式行為」的程式。你寫好一個函式後,再寫一個測試去呼叫它、比對結果;之後每次改程式,只要跑一次測試就知道有沒有改壞。
可以把它想成「自動化的對答案」:題目(輸入)與標準答案(預期輸出)寫好,交給電腦反覆批改。
Go 不需要安裝任何測試框架:標準庫的 testing 套件加上 go test 指令就是全部。
元素規則
測試檔檔名以 _test.go 結尾,放在被測程式的同一個目錄
測試函式名稱為 TestXxx(Test 後接大寫字母開頭的名稱),簽名為 func(t *testing.T)
執行在套件目錄下執行 go test

_test.go 檔只在 go test 時編譯,不會被 go build 編進正式的執行檔。

撰寫與執行測試


_test.go 與 TestXxx


被測程式與測試檔放在同一個目錄、同一個套件(package)。測試函式接收一個 *testing.T,透過它回報失敗。Go 沒有 assert 語法,判斷就用一般的 if。
被測程式 calc.go:
  1. package calc
  2. func Add(a, b int) int {
  3. return a + b
  4. }

測試檔 calc_test.go:
  1. package calc
  2. import "testing"
  3. func TestAdd(t *testing.T) {
  4. got := Add(2, 3)
  5. if got != 5 {
  6. t.Errorf("Add(2, 3) = %d, want 5", got)
  7. }
  8. }

模組設定 go.mod:
  1. module example.com/calc
  2. go 1.26

執行:
  1. go test
  2. go test -v

輸出:
  1. PASS
  2. ok example.com/calc 0.280s
  3. === RUN TestAdd
  4. --- PASS: TestAdd (0.00s)
  5. PASS
  6. ok example.com/calc 0.051s

不加旗標時只印總結;-v(verbose)會列出每個測試的名稱與結果。最後一欄是執行耗時,數字因機器而異。
錯誤訊息慣例寫成 函式(輸入) = 實際值, want 預期值,失敗時一眼就能看出差在哪。

t.Error 與 t.Errorf:記錄失敗後繼續


t.Error 與 t.Errorf 會把這個測試標記為失敗、印出訊息,但繼續往下執行。適合多個彼此獨立的檢查:一次跑完,看到所有失敗的地方。
t.Log 只印訊息不影響結果;測試通過時不會顯示,失敗或加 -v 時才看得到。
被測程式 calc.go(故意埋了一個 bug:條件寫成 n < -1):
  1. package calc
  2. func Abs(n int) int {
  3. if n < -1 {
  4. return -n
  5. }
  6. return n
  7. }

測試檔 calc_test.go:
  1. package calc
  2. import "testing"
  3. func TestAbs(t *testing.T) {
  4. if got := Abs(5); got != 5 {
  5. t.Errorf("Abs(5) = %d, want 5", got)
  6. }
  7. if got := Abs(-1); got != 1 {
  8. t.Errorf("Abs(-1) = %d, want 1", got)
  9. }
  10. if got := Abs(0); got != 0 {
  11. t.Errorf("Abs(0) = %d, want 0", got)
  12. }
  13. t.Log("all checks done")
  14. }

執行:
  1. go test

輸出:
  1. --- FAIL: TestAbs (0.00s)
  2. calc_test.go:10: Abs(-1) = -1, want 1
  3. calc_test.go:15: all checks done
  4. FAIL
  5. exit status 1
  6. FAIL example.com/calc 0.239s

每則訊息前面會標出檔名與行號。第 10 行失敗後,第 15 行的 t.Log 仍然執行,證明 t.Errorf 不會中斷測試。go test 失敗時結束碼不為 0,CI 會據此判定失敗。

t.Fatal 與 t.Fatalf:失敗就立刻停止


t.Fatal 與 t.Fatalf 會標記失敗並立刻結束這個測試函式(其他測試函式照常執行)。用在「後面的檢查依賴這一步成功」的情況,例如解析失敗時 cfg 是 nil,繼續存取 cfg.Port 只會 panic。
被測程式 config.go:
  1. package calc
  2. import (
  3. "errors"
  4. "strings"
  5. )
  6. type Config struct {
  7. Name string
  8. Port string
  9. }
  10. func Parse(s string) (*Config, error) {
  11. name, port, ok := strings.Cut(s, ":")
  12. if !ok {
  13. return nil, errors.New("missing colon")
  14. }
  15. return &Config{Name: name, Port: port}, nil
  16. }

測試檔 config_test.go:
  1. package calc
  2. import "testing"
  3. func TestParse(t *testing.T) {
  4. cfg, err := Parse("localhost:8080")
  5. if err != nil {
  6. t.Fatalf("Parse returned error: %v", err)
  7. }
  8. if cfg.Port != "8080" {
  9. t.Errorf("Port = %q, want %q", cfg.Port, "8080")
  10. }
  11. }
  12. func TestParseBad(t *testing.T) {
  13. cfg, err := Parse("localhost")
  14. if err != nil {
  15. t.Fatalf("Parse returned error: %v", err)
  16. }
  17. t.Log("this line never runs")
  18. if cfg.Port != "" {
  19. t.Errorf("Port = %q", cfg.Port)
  20. }
  21. }

執行:
  1. go test

輸出:
  1. --- FAIL: TestParseBad (0.00s)
  2. config_test.go:18: Parse returned error: missing colon
  3. FAIL
  4. exit status 1
  5. FAIL example.com/calc 0.237s

TestParse 通過所以沒有出現;TestParseBad 在第 18 行停下,t.Log 那行沒有執行。
注意:t.Fatal、t.FailNow、t.Skip 必須在執行測試函式的那個 goroutine 呼叫;在自己另開的 goroutine 裡呼叫不會中止測試。在 goroutine 中回報錯誤請用 t.Error。
方法標記失敗繼續執行
t.Log / t.Logf否是
t.Error / t.Errorf是是
t.Fatal / t.Fatalf是否

go test 常用旗標


go test 預設測試目前目錄的套件。常用旗標:
旗標作用
-v列出每個測試的名稱與結果
-run <regexp>只執行名稱符合正規表示式的測試
-count=1不使用快取,強制重跑
./...測試目前目錄與所有子目錄的套件

被測程式 textx.go:
  1. package textx
  2. import "strings"
  3. func Upper(s string) string {
  4. return strings.ToUpper(s)
  5. }
  6. func Reverse(s string) string {
  7. r := []rune(s)
  8. for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
  9. r[i], r[j] = r[j], r[i]
  10. }
  11. return string(r)
  12. }

測試檔 textx_test.go:
  1. package textx
  2. import "testing"
  3. func TestUpper(t *testing.T) {
  4. if got := Upper("go"); got != "GO" {
  5. t.Errorf("Upper(%q) = %q, want %q", "go", got, "GO")
  6. }
  7. }
  8. func TestUpperEmpty(t *testing.T) {
  9. if got := Upper(""); got != "" {
  10. t.Errorf("Upper(%q) = %q, want empty", "", got)
  11. }
  12. }
  13. func TestReverse(t *testing.T) {
  14. if got := Reverse("你好"); got != "好你" {
  15. t.Errorf("Reverse(%q) = %q, want %q", "你好", got, "好你")
  16. }
  17. }

執行(go.mod 的 module 為 example.com/textx):
  1. go test -v -run Upper
  2. go test -count=1 ./...
  3. go test ./...
  4. go test ./...

輸出:
  1. === RUN TestUpper
  2. --- PASS: TestUpper (0.00s)
  3. === RUN TestUpperEmpty
  4. --- PASS: TestUpperEmpty (0.00s)
  5. PASS
  6. ok example.com/textx 0.242s
  7. ok example.com/textx 0.054s
  8. ok example.com/textx 0.048s
  9. ok example.com/textx (cached)

-run Upper 是正規表示式,TestUpper 與 TestUpperEmpty 都符合,TestReverse 被略過。
最後兩行展示測試快取:程式碼與旗標都沒變時,go test 直接沿用上次的結果並標示 (cached)。要強制重跑就加 -count=1。

重點整理


  • 測試檔以 _test.go 結尾、與被測程式同目錄;測試函式為 func TestXxx(t *testing.T)
  • 判斷用一般 if,失敗訊息寫成「實際值, want 預期值」
  • t.Error 記錄失敗後繼續;t.Fatal 記錄失敗後立刻結束該測試
  • go test -v 看細節、-run 篩選測試、-count=1 略過快取、./... 測整個模組
  • 想一次測多組輸入,改用表格驅動測試

資料來源