# 測試覆蓋率

本頁說明如何用 `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`：

```go
package shop

import "errors"

func Discount(total int, member bool) int {
	if total >= 1000 {
		total = total * 9 / 10
	}
	if member {
		total -= 50
	}
	return total
}

func Shipping(total int) (int, error) {
	if total < 0 {
		return 0, errors.New("negative total")
	}
	if total >= 500 {
		return 0, nil
	}
	return 60, nil
}
```

測試檔 `shop_test.go`（每個函式只測一種情況）：

```go
package shop

import "testing"

func TestDiscount(t *testing.T) {
	if got := Discount(1000, false); got != 900 {
		t.Errorf("Discount(1000, false) = %d, want 900", got)
	}
}

func TestShipping(t *testing.T) {
	got, err := Shipping(100)
	if err != nil || got != 60 {
		t.Errorf("Shipping(100) = %d, %v, want 60, nil", got, err)
	}
}
```

執行（`go.mod` 的 module 為 `example.com/shop`）：

```bash
go test -cover
```

輸出：

```text
PASS
coverage: 70.0% of statements
ok  	example.com/shop	0.245s
```

10 個敘述中有 7 個被執行過。最後的耗時數字因機器而異。

`./...` 也能搭配 `-cover`，一次看整個模組每個套件的覆蓋率。

### -coverprofile 與 go tool cover -func

百分比只說「有多少沒測到」，不說「哪裡沒測到」。`-coverprofile` 把每一段程式碼的執行紀錄寫進檔案，再用 `go tool cover -func` 按函式列出覆蓋率。

被測程式與測試檔同上。執行：

```bash
go test -coverprofile=cover.out
cat cover.out
go tool cover -func=cover.out
```

輸出：

```text
PASS
coverage: 70.0% of statements
ok  	example.com/shop	0.051s
mode: set
example.com/shop/shop.go:5.43,6.19 1 1
example.com/shop/shop.go:6.19,8.3 1 1
example.com/shop/shop.go:9.2,9.12 1 1
example.com/shop/shop.go:9.12,11.3 1 0
example.com/shop/shop.go:12.2,12.14 1 1
example.com/shop/shop.go:15.39,16.15 1 1
example.com/shop/shop.go:16.15,18.3 1 0
example.com/shop/shop.go:19.2,19.18 1 1
example.com/shop/shop.go:19.18,21.3 1 0
example.com/shop/shop.go:22.2,22.16 1 1
example.com/shop/shop.go:5:	Discount	80.0%
example.com/shop/shop.go:15:	Shipping	60.0%
total:				(statements)	70.0%
```

`cover.out` 每一行代表一個程式區塊，格式為 `檔案:起始行.欄,結束行.欄 敘述數 執行次數`。最後一欄是 `0` 的區塊就是沒被執行過的：

| 區塊 | 對應程式 | 缺少的測試 |
| --- | --- | --- |
| `9.12,11.3` | `total -= 50` | 會員（`member` 為 `true`） |
| `16.15,18.3` | `return 0, errors.New(...)` | 負數金額 |
| `19.18,21.3` | `return 0, nil` | 滿 500 免運 |

### go tool cover -html

`-html` 產生一份 HTML 報告，原始碼以顏色標示：綠色是有執行的、紅色是沒執行的、灰色是不計入的（例如宣告）。比對 `cover.out` 的行號直覺得多。

不加 `-o` 時會直接用瀏覽器開啟；加 `-o` 則寫成檔案，方便在 CI 中保存。

被測程式與測試檔同上。執行：

```bash
go test -coverprofile=cover.out
go tool cover -html=cover.out -o cover.html
ls cover.html
```

輸出：

```text
PASS
coverage: 70.0% of statements
ok  	example.com/shop	0.051s
cover.html
```

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

### -covermode=count 計算執行次數

`-covermode` 決定覆蓋資料記錄什麼：

| 模式 | 記錄內容 |
| --- | --- |
| `set` | 有沒有執行過（預設） |
| `count` | 執行了幾次 |
| `atomic` | 執行了幾次，且在並行下計數正確；搭配 `-race` 時為預設 |

`count` 模式在 HTML 報告中會用綠色深淺表示執行次數，可以看出熱點。

把測試改寫成[表格驅動測試](/testing-table-driven)，補上缺少的情況。測試檔 `shop_test.go`（被測程式同上）：

```go
package shop

import "testing"

func TestDiscount(t *testing.T) {
	tests := []struct {
		total  int
		member bool
		want   int
	}{
		{1000, false, 900},
		{1000, true, 850},
		{200, true, 150},
		{200, false, 200},
	}
	for _, tt := range tests {
		if got := Discount(tt.total, tt.member); got != tt.want {
			t.Errorf("Discount(%d, %v) = %d, want %d", tt.total, tt.member, got, tt.want)
		}
	}
}

func TestShipping(t *testing.T) {
	tests := []struct {
		total   int
		want    int
		wantErr bool
	}{
		{-1, 0, true},
		{100, 60, false},
		{500, 0, false},
	}
	for _, tt := range tests {
		got, err := Shipping(tt.total)
		if (err != nil) != tt.wantErr || got != tt.want {
			t.Errorf("Shipping(%d) = %d, %v", tt.total, got, err)
		}
	}
}
```

執行：

```bash
go test -covermode=count -coverprofile=cover.out
cat cover.out
go tool cover -func=cover.out
```

輸出：

```text
PASS
coverage: 100.0% of statements
ok  	example.com/shop	0.231s
mode: count
example.com/shop/shop.go:5.43,6.19 1 4
example.com/shop/shop.go:6.19,8.3 1 2
example.com/shop/shop.go:9.2,9.12 1 4
example.com/shop/shop.go:9.12,11.3 1 2
example.com/shop/shop.go:12.2,12.14 1 4
example.com/shop/shop.go:15.39,16.15 1 3
example.com/shop/shop.go:16.15,18.3 1 1
example.com/shop/shop.go:19.2,19.18 1 2
example.com/shop/shop.go:19.18,21.3 1 1
example.com/shop/shop.go:22.2,22.16 1 1
example.com/shop/shop.go:5:	Discount	100.0%
example.com/shop/shop.go:15:	Shipping	100.0%
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`）：

```go
package main

import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) > 1 && os.Args[1] == "-tw" {
		fmt.Println("你好")
		return
	}
	fmt.Println("hello")
}
```

執行：

```bash
go build -cover -o greet .
mkdir -p covdata
GOCOVERDIR=covdata ./greet
GOCOVERDIR=covdata ./greet -tw
go tool covdata percent -i=covdata
go tool covdata textfmt -i=covdata -o=cover.out
go tool cover -func=cover.out
```

輸出：

```text
hello
你好
	example.com/greet		coverage: 100.0% of statements
example.com/greet/main.go:8:	main		100.0%
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` 量測實際執行的程式
- 覆蓋率用來找沒測到的分支，不是越高就代表測試越好

## 資料來源

- [gopl-zh/gopl-zh.github.com（《Go 語言聖經》中譯本，章節架構參考）](https://github.com/gopl-zh/gopl-zh.github.com)
- [The Go Programming Language Specification](https://go.dev/ref/spec)
- [Go 官方文件](https://go.dev/doc/)
- [Go 官方部落格](https://go.dev/blog/)
