測試覆蓋率

最後更新


本頁說明如何用 go test -cover 量測測試覆蓋率,並用 go tool cover 找出哪些程式碼沒被測到。

什麼是測試覆蓋率


測試覆蓋率(test coverage)是「跑測試時,有多少比例的程式碼被執行過」。Go 以「敘述(statement)」為單位計算:一個 if 分支裡的程式從沒被執行,就算沒覆蓋。
它像一張「檢查過的房間地圖」:覆蓋率 70% 代表還有 30% 的房間沒人走進去過,那裡的 bug 測試抓不到。
注意:覆蓋率高不代表測試好。程式碼被執行過,不表示結果有被正確檢查。覆蓋率最有用的地方是找出完全沒測到的分支,而不是追求 100% 這個數字。
指令用途
go test -cover印出覆蓋率百分比
go test -coverprofile=cover.out把逐行覆蓋資料寫入檔案
go tool cover -func=cover.out列出每個函式的覆蓋率
go tool cover -html=cover.out產生以顏色標示的 HTML 報告

量測與分析覆蓋率


go test -cover


加上 -cover 旗標,go test 會在測試通過後印出該套件的敘述覆蓋率。
被測程式 shop.go:
  1. package shop
  2. import "errors"
  3. func Discount(total int, member bool) int {
  4. if total >= 1000 {
  5. total = total * 9 / 10
  6. }
  7. if member {
  8. total -= 50
  9. }
  10. return total
  11. }
  12. func Shipping(total int) (int, error) {
  13. if total < 0 {
  14. return 0, errors.New("negative total")
  15. }
  16. if total >= 500 {
  17. return 0, nil
  18. }
  19. return 60, nil
  20. }

測試檔 shop_test.go(每個函式只測一種情況):
  1. package shop
  2. import "testing"
  3. func TestDiscount(t *testing.T) {
  4. if got := Discount(1000, false); got != 900 {
  5. t.Errorf("Discount(1000, false) = %d, want 900", got)
  6. }
  7. }
  8. func TestShipping(t *testing.T) {
  9. got, err := Shipping(100)
  10. if err != nil || got != 60 {
  11. t.Errorf("Shipping(100) = %d, %v, want 60, nil", got, err)
  12. }
  13. }

執行(go.mod 的 module 為 example.com/shop):
  1. go test -cover

輸出:
  1. PASS
  2. coverage: 70.0% of statements
  3. ok example.com/shop 0.245s

10 個敘述中有 7 個被執行過。最後的耗時數字因機器而異。
./... 也能搭配 -cover,一次看整個模組每個套件的覆蓋率。

-coverprofile 與 go tool cover -func


百分比只說「有多少沒測到」,不說「哪裡沒測到」。-coverprofile 把每一段程式碼的執行紀錄寫進檔案,再用 go tool cover -func 按函式列出覆蓋率。
被測程式與測試檔同上。執行:
  1. go test -coverprofile=cover.out
  2. cat cover.out
  3. go tool cover -func=cover.out

輸出:
  1. PASS
  2. coverage: 70.0% of statements
  3. ok example.com/shop 0.051s
  4. mode: set
  5. example.com/shop/shop.go:5.43,6.19 1 1
  6. example.com/shop/shop.go:6.19,8.3 1 1
  7. example.com/shop/shop.go:9.2,9.12 1 1
  8. example.com/shop/shop.go:9.12,11.3 1 0
  9. example.com/shop/shop.go:12.2,12.14 1 1
  10. example.com/shop/shop.go:15.39,16.15 1 1
  11. example.com/shop/shop.go:16.15,18.3 1 0
  12. example.com/shop/shop.go:19.2,19.18 1 1
  13. example.com/shop/shop.go:19.18,21.3 1 0
  14. example.com/shop/shop.go:22.2,22.16 1 1
  15. example.com/shop/shop.go:5: Discount 80.0%
  16. example.com/shop/shop.go:15: Shipping 60.0%
  17. total: (statements) 70.0%

cover.out 每一行代表一個程式區塊,格式為 檔案:起始行.欄,結束行.欄 敘述數 執行次數。最後一欄是 0 的區塊就是沒被執行過的:
區塊對應程式缺少的測試
9.12,11.3total -= 50會員(member 為 true)
16.15,18.3return 0, errors.New(...)負數金額
19.18,21.3return 0, nil滿 500 免運

go tool cover -html


-html 產生一份 HTML 報告,原始碼以顏色標示:綠色是有執行的、紅色是沒執行的、灰色是不計入的(例如宣告)。比對 cover.out 的行號直覺得多。
不加 -o 時會直接用瀏覽器開啟;加 -o 則寫成檔案,方便在 CI 中保存。
被測程式與測試檔同上。執行:
  1. go test -coverprofile=cover.out
  2. go tool cover -html=cover.out -o cover.html
  3. ls cover.html

輸出:
  1. PASS
  2. coverage: 70.0% of statements
  3. ok example.com/shop 0.051s
  4. cover.html

用瀏覽器打開 cover.html,total -= 50、return 0, errors.New("negative total")、return 0, nil 三段會以紅色顯示,其餘程式為綠色。

-covermode=count 計算執行次數


-covermode 決定覆蓋資料記錄什麼:
模式記錄內容
set有沒有執行過(預設)
count執行了幾次
atomic執行了幾次,且在並行下計數正確;搭配 -race 時為預設

count 模式在 HTML 報告中會用綠色深淺表示執行次數,可以看出熱點。
把測試改寫成表格驅動測試,補上缺少的情況。測試檔 shop_test.go(被測程式同上):
  1. package shop
  2. import "testing"
  3. func TestDiscount(t *testing.T) {
  4. tests := []struct {
  5. total int
  6. member bool
  7. want int
  8. }{
  9. {1000, false, 900},
  10. {1000, true, 850},
  11. {200, true, 150},
  12. {200, false, 200},
  13. }
  14. for _, tt := range tests {
  15. if got := Discount(tt.total, tt.member); got != tt.want {
  16. t.Errorf("Discount(%d, %v) = %d, want %d", tt.total, tt.member, got, tt.want)
  17. }
  18. }
  19. }
  20. func TestShipping(t *testing.T) {
  21. tests := []struct {
  22. total int
  23. want int
  24. wantErr bool
  25. }{
  26. {-1, 0, true},
  27. {100, 60, false},
  28. {500, 0, false},
  29. }
  30. for _, tt := range tests {
  31. got, err := Shipping(tt.total)
  32. if (err != nil) != tt.wantErr || got != tt.want {
  33. t.Errorf("Shipping(%d) = %d, %v", tt.total, got, err)
  34. }
  35. }
  36. }

執行:
  1. go test -covermode=count -coverprofile=cover.out
  2. cat cover.out
  3. go tool cover -func=cover.out

輸出:
  1. PASS
  2. coverage: 100.0% of statements
  3. ok example.com/shop 0.231s
  4. mode: count
  5. example.com/shop/shop.go:5.43,6.19 1 4
  6. example.com/shop/shop.go:6.19,8.3 1 2
  7. example.com/shop/shop.go:9.2,9.12 1 4
  8. example.com/shop/shop.go:9.12,11.3 1 2
  9. example.com/shop/shop.go:12.2,12.14 1 4
  10. example.com/shop/shop.go:15.39,16.15 1 3
  11. example.com/shop/shop.go:16.15,18.3 1 1
  12. example.com/shop/shop.go:19.2,19.18 1 2
  13. example.com/shop/shop.go:19.18,21.3 1 1
  14. example.com/shop/shop.go:22.2,22.16 1 1
  15. example.com/shop/shop.go:5: Discount 100.0%
  16. example.com/shop/shop.go:15: Shipping 100.0%
  17. total: (statements) 100.0%

最後一欄變成執行次數:Discount 被呼叫 4 次,其中 2 次進入滿千打折的分支。
預設只計算被測套件本身的覆蓋率;想把其他套件也算進去,用 -coverpkg=./...。

go build -cover:量測整支程式


Go 1.20 起,也能量測「實際執行程式」時的覆蓋率,適合整合測試(integration test):用 go build -cover 建置,執行時以環境變數 GOCOVERDIR 指定資料輸出目錄,再用 go tool covdata 分析。
程式 main.go(go.mod 的 module 為 example.com/greet):
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. if len(os.Args) > 1 && os.Args[1] == "-tw" {
  8. fmt.Println("你好")
  9. return
  10. }
  11. fmt.Println("hello")
  12. }

執行:
  1. go build -cover -o greet .
  2. mkdir -p covdata
  3. GOCOVERDIR=covdata ./greet
  4. GOCOVERDIR=covdata ./greet -tw
  5. go tool covdata percent -i=covdata
  6. go tool covdata textfmt -i=covdata -o=cover.out
  7. go tool cover -func=cover.out

輸出:
  1. hello
  2. 你好
  3. example.com/greet coverage: 100.0% of statements
  4. example.com/greet/main.go:8: main 100.0%
  5. total: (statements) 100.0%

兩次執行各走一個分支,資料累積在 covdata 目錄,合併後達到 100%。textfmt 把它轉成和 -coverprofile 相同的格式,就能沿用 go tool cover 的各種報告。

重點整理


  • go test -cover 印出敘述覆蓋率百分比
  • -coverprofile=cover.out 寫出逐區塊資料,go tool cover -func 看函式覆蓋率,-html 看紅綠標示
  • -covermode 有 set、count、atomic 三種;count 可看出執行次數
  • Go 1.20 起可用 go build -cover 加 GOCOVERDIR 量測實際執行的程式
  • 覆蓋率用來找沒測到的分支,不是越高就代表測試越好

資料來源