# 單元測試

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

## 為什麼要寫單元測試

單元測試（unit test）是一段「自動檢查程式行為」的程式。你寫好一個函式後，再寫一個測試去呼叫它、比對結果；之後每次改程式，只要跑一次測試就知道有沒有改壞。

可以把它想成「自動化的對答案」：題目（輸入）與標準答案（預期輸出）寫好，交給電腦反覆批改。

Go 不需要安裝任何測試框架：標準庫的 [`testing`](/pkg-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`：

```go
package calc

func Add(a, b int) int {
	return a + b
}
```

測試檔 `calc_test.go`：

```go
package calc

import "testing"

func TestAdd(t *testing.T) {
	got := Add(2, 3)
	if got != 5 {
		t.Errorf("Add(2, 3) = %d, want 5", got)
	}
}
```

模組設定 `go.mod`：

```text
module example.com/calc

go 1.26
```

執行：

```bash
go test
go test -v
```

輸出：

```text
PASS
ok  	example.com/calc	0.280s
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
PASS
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`）：

```go
package calc

func Abs(n int) int {
	if n < -1 {
		return -n
	}
	return n
}
```

測試檔 `calc_test.go`：

```go
package calc

import "testing"

func TestAbs(t *testing.T) {
	if got := Abs(5); got != 5 {
		t.Errorf("Abs(5) = %d, want 5", got)
	}
	if got := Abs(-1); got != 1 {
		t.Errorf("Abs(-1) = %d, want 1", got)
	}
	if got := Abs(0); got != 0 {
		t.Errorf("Abs(0) = %d, want 0", got)
	}
	t.Log("all checks done")
}
```

執行：

```bash
go test
```

輸出：

```text
--- FAIL: TestAbs (0.00s)
    calc_test.go:10: Abs(-1) = -1, want 1
    calc_test.go:15: all checks done
FAIL
exit status 1
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`：

```go
package calc

import (
	"errors"
	"strings"
)

type Config struct {
	Name string
	Port string
}

func Parse(s string) (*Config, error) {
	name, port, ok := strings.Cut(s, ":")
	if !ok {
		return nil, errors.New("missing colon")
	}
	return &Config{Name: name, Port: port}, nil
}
```

測試檔 `config_test.go`：

```go
package calc

import "testing"

func TestParse(t *testing.T) {
	cfg, err := Parse("localhost:8080")
	if err != nil {
		t.Fatalf("Parse returned error: %v", err)
	}
	if cfg.Port != "8080" {
		t.Errorf("Port = %q, want %q", cfg.Port, "8080")
	}
}

func TestParseBad(t *testing.T) {
	cfg, err := Parse("localhost")
	if err != nil {
		t.Fatalf("Parse returned error: %v", err)
	}
	t.Log("this line never runs")
	if cfg.Port != "" {
		t.Errorf("Port = %q", cfg.Port)
	}
}
```

執行：

```bash
go test
```

輸出：

```text
--- FAIL: TestParseBad (0.00s)
    config_test.go:18: Parse returned error: missing colon
FAIL
exit status 1
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`：

```go
package textx

import "strings"

func Upper(s string) string {
	return strings.ToUpper(s)
}

func Reverse(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}
```

測試檔 `textx_test.go`：

```go
package textx

import "testing"

func TestUpper(t *testing.T) {
	if got := Upper("go"); got != "GO" {
		t.Errorf("Upper(%q) = %q, want %q", "go", got, "GO")
	}
}

func TestUpperEmpty(t *testing.T) {
	if got := Upper(""); got != "" {
		t.Errorf("Upper(%q) = %q, want empty", "", got)
	}
}

func TestReverse(t *testing.T) {
	if got := Reverse("你好"); got != "好你" {
		t.Errorf("Reverse(%q) = %q, want %q", "你好", got, "好你")
	}
}
```

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

```bash
go test -v -run Upper
go test -count=1 ./...
go test ./...
go test ./...
```

輸出：

```text
=== RUN   TestUpper
--- PASS: TestUpper (0.00s)
=== RUN   TestUpperEmpty
--- PASS: TestUpperEmpty (0.00s)
PASS
ok  	example.com/textx	0.242s
ok  	example.com/textx	0.054s
ok  	example.com/textx	0.048s
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` 略過快取、`./...` 測整個模組
- 想一次測多組輸入，改用[表格驅動測試](/testing-table-driven)

## 資料來源

- [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/)
