testify
最後更新
testify 是 Go 最常用的測試輔助庫,提供好讀的斷言(assertion)、測試套組(suite)與 mock 物件。
- module:
github.com/stretchr/testify - 本書版本:v1.12.1(使用
assert、require、suite、mock四個套件)
這個庫做什麼
標準庫的
testing 只給你 t.Errorf 與 t.Fatalf,判斷要自己寫 if,失敗訊息也要自己組(見單元測試)。比對結構體、切片、錯誤鏈時,程式很快就變得冗長。testify 把這些常見判斷包成一行函式,失敗時自動印出「預期值、實際值、差異(diff)」:
| 需求 | 只用 testing | 用 testify |
|---|---|---|
| 比對兩個值 | if got != want { t.Errorf(...) } | assert.Equal(t, want, got) |
| 比對結構體或切片 | 自己用 reflect.DeepEqual | assert.Equal 直接比,失敗附 diff |
| 檢查錯誤鏈 | if !errors.Is(err, X) {...} | assert.ErrorIs(t, err, X) |
| 每個測試前後的準備與清理 | 自己寫輔助函式 | suite 的 SetupTest/TearDownTest |
| 假的相依物件 | 自己手寫假實作 | mock.Mock 記錄呼叫與回傳值 |
testify 只是輔助:測試仍然是一般的
TestXxx(t *testing.T),用 go test 執行,可以和原本的 if 寫法混用。安裝
- go get github.com/stretchr/testify@v1.12.1
testify 的最新主版本仍是 v1,import 路徑沒有
/v2。官方 README 說明 v1 會持續維護、不接受破壞性變更,所以照著 github.com/stretchr/testify/... 匯入即可。本頁每個範例都是一個獨立的模組,
go.mod 長這樣(模組名稱依範例而不同):- module example.com/calc
- go 1.26
- require github.com/stretchr/testify v1.12.1
assert 與 require
testify 有兩個斷言套件,函式名稱與參數完全相同,差別只在「失敗後要不要繼續」:
| 套件 | 失敗時呼叫 | 失敗後 | 適合 |
|---|---|---|---|
assert | t.Errorf | 繼續執行,函式回傳 false | 彼此獨立的多個檢查 |
require | t.FailNow | 立刻結束這個測試 | 後面的程式依賴這個結果(例如 err 不為 nil 時指標是 nil) |
所有斷言的參數順序都是
(t, 預期值, 實際值, 額外訊息...),預期值在前。assert:失敗後繼續
被測檔
calc.go:- package calc
- import "errors"
- var ErrDivByZero = errors.New("division by zero")
- func Divide(a, b int) (int, error) {
- if b == 0 {
- return 0, ErrDivByZero
- }
- return a / b, nil
- }
測試檔
calc_test.go(故意用除以 0 製造失敗):- package calc
- import (
- "testing"
- "github.com/stretchr/testify/assert"
- )
- func TestDivide(t *testing.T) {
- got, err := Divide(10, 0)
- assert.NoError(t, err)
- assert.Equal(t, 5, got)
- t.Log("still running")
- }
執行:
- go test -v .
輸出:
- === RUN TestDivide
- calc_test.go:11:
- Error Trace: .../calc/calc_test.go:11
- Error: Received unexpected error:
- division by zero
- Test: TestDivide
- calc_test.go:12:
- Error Trace: .../calc/calc_test.go:12
- Error: Not equal:
- expected: 5
- actual : 0
- Test: TestDivide
- calc_test.go:13: still running
- --- FAIL: TestDivide (0.00s)
- FAIL
- FAIL example.com/calc 0.225s
- FAIL
兩個斷言都失敗,而且最後的
t.Log 仍有執行。Error Trace 實際會印出檔案的完整路徑,這裡以 ... 省略前段;最後一欄的耗時數字因機器而異。require:失敗就停
被測檔
user.go:找不到使用者時回傳 nil 指標與錯誤。- package user
- import "errors"
- var ErrNotFound = errors.New("user not found")
- type User struct {
- ID int
- Name string
- }
- var users = map[int]*User{1: {ID: 1, Name: "Alice"}}
- func Find(id int) (*User, error) {
- u, ok := users[id]
- if !ok {
- return nil, ErrNotFound
- }
- return u, nil
- }
測試檔
user_test.go:- package user
- import (
- "testing"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
- )
- func TestFind(t *testing.T) {
- u, err := Find(2)
- require.NoError(t, err)
- assert.Equal(t, "Alice", u.Name)
- }
執行
go test -v .,輸出:- === RUN TestFind
- user_test.go:12:
- Error Trace: .../user/user_test.go:12
- Error: Received unexpected error:
- user not found
- Test: TestFind
- --- FAIL: TestFind (0.00s)
- FAIL
- FAIL example.com/user 0.241s
- FAIL
require.NoError 失敗後測試立即結束,u.Name 那行沒有執行。注意:如果這裡改用
assert.NoError,程式會繼續執行到 u.Name,而 u 是 nil,測試會因為 nil 指標而 panic。檢查錯誤、檢查長度這類「後面要靠它」的前置條件用 require,其餘用 assert。常用斷言
以下斷言
assert 與 require 都有,簽名相同(require 版沒有回傳值)。Equal:比對任意值
Equal 用 ObjectsAreEqual 深度比對,結構體、切片、映射都能直接比;失敗時附上逐欄位的 diff。簽名:
- func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
被測檔
profile.go:- package profile
- import "strings"
- type Profile struct {
- Name string
- Email string
- Tags []string
- }
- func Normalize(p Profile) Profile {
- p.Name = strings.TrimSpace(p.Name)
- p.Email = strings.ToLower(p.Email)
- return p
- }
測試檔
profile_test.go(預期值故意多一個 tag,示範失敗時的 diff):- package profile
- import (
- "testing"
- "github.com/stretchr/testify/assert"
- )
- func TestNormalize(t *testing.T) {
- got := Normalize(Profile{Name: " Bob ", Email: "Bob@Example.COM", Tags: []string{"go"}})
- want := Profile{Name: "Bob", Email: "bob@example.com", Tags: []string{"go", "admin"}}
- assert.Equal(t, want, got)
- }
執行
go test -v .,輸出:- === RUN TestNormalize
- profile_test.go:12:
- Error Trace: .../profile/profile_test.go:12
- Error: Not equal:
- expected: profile.Profile{Name:"Bob", Email:"bob@example.com", Tags:[]string{"go", "admin"}}
- actual : profile.Profile{Name:"Bob", Email:"bob@example.com", Tags:[]string{"go"}}
-
- Diff:
- --- Expected
- +++ Actual
- @@ -3,5 +3,4 @@
- Email: (string) (len=15) "bob@example.com",
- - Tags: ([]string) (len=2) {
- - (string) (len=2) "go",
- - (string) (len=5) "admin"
- + Tags: ([]string) (len=1) {
- + (string) (len=2) "go"
- }
- Test: TestNormalize
- --- FAIL: TestNormalize (0.00s)
- FAIL
- FAIL example.com/profile 0.236s
- FAIL
- 開頭是預期值、+ 開頭是實際值,一眼看出差在 Tags。注意:
Equal 會比較型別,int(5) 與 int64(5) 不相等。NoError 與 ErrorIs:檢查錯誤
NoError(t, err):err必須是nilErrorIs(t, err, target):等同errors.Is(err, target),能穿透%w包裝的錯誤鏈(見錯誤包裝)EqualError(t, err, "..."):比對err.Error()的完整字串
簽名:
- func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool
- func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool
被測檔
config.go:- package config
- import (
- "errors"
- "fmt"
- "strconv"
- )
- var ErrMissing = errors.New("missing key")
- func Port(env map[string]string) (int, error) {
- v, ok := env["PORT"]
- if !ok {
- return 0, fmt.Errorf("config PORT: %w", ErrMissing)
- }
- return strconv.Atoi(v)
- }
測試檔
config_test.go:- package config
- import (
- "testing"
- "github.com/stretchr/testify/assert"
- )
- func TestPortOK(t *testing.T) {
- p, err := Port(map[string]string{"PORT": "8080"})
- assert.NoError(t, err)
- assert.Equal(t, 8080, p)
- }
- func TestPortMissing(t *testing.T) {
- _, err := Port(map[string]string{})
- assert.ErrorIs(t, err, ErrMissing)
- assert.EqualError(t, err, "config PORT: missing key")
- }
執行
go test -v .,輸出:- === RUN TestPortOK
- --- PASS: TestPortOK (0.00s)
- === RUN TestPortMissing
- --- PASS: TestPortMissing (0.00s)
- PASS
- ok example.com/config 0.238s
判斷「是哪一種錯誤」優先用
ErrorIs;錯誤訊息字串之後可能改寫,EqualError 只在訊息本身就是規格時使用。Contains 與 Len:檢查集合
Contains(t, s, x):字串含子字串、切片含元素、映射含 keyNotContains:相反Len(t, obj, n):字串、切片、映射、channel 的長度為n
簽名:
- func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
- func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool
被測檔
words.go:- package words
- import "strings"
- func Count(text string) map[string]int {
- m := map[string]int{}
- for _, w := range strings.Fields(strings.ToLower(text)) {
- m[w]++
- }
- return m
- }
- func Unique(text string) []string {
- var out []string
- seen := map[string]bool{}
- for _, w := range strings.Fields(strings.ToLower(text)) {
- if !seen[w] {
- seen[w] = true
- out = append(out, w)
- }
- }
- return out
- }
測試檔
words_test.go:- package words
- import (
- "testing"
- "github.com/stretchr/testify/assert"
- )
- func TestUnique(t *testing.T) {
- got := Unique("Go is fun and go is fast")
- assert.Len(t, got, 5)
- assert.Contains(t, got, "fun")
- assert.NotContains(t, got, "Go")
- }
- func TestCount(t *testing.T) {
- got := Count("a b a")
- assert.Len(t, got, 2)
- assert.Contains(t, got, "a")
- assert.Contains(t, "hello, gopher", "gopher")
- }
執行
go test -v .,輸出:- === RUN TestUnique
- --- PASS: TestUnique (0.00s)
- === RUN TestCount
- --- PASS: TestCount (0.00s)
- PASS
- ok example.com/words 0.242s
Contains 用在映射時只檢查 key,不看 value。JSONEq:比對 JSON 內容
直接比 JSON 字串會被 key 順序與空白影響。
JSONEq 先把兩邊解析成資料再比較,只看內容是否相同。簽名:
- func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool
被測檔
api.go:- package api
- import "encoding/json"
- type Item struct {
- ID int `json:"id"`
- Name string `json:"name"`
- Price float64 `json:"price"`
- }
- func Encode(it Item) (string, error) {
- b, err := json.Marshal(it)
- return string(b), err
- }
測試檔
api_test.go:- package api
- import (
- "testing"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
- )
- func TestEncode(t *testing.T) {
- got, err := Encode(Item{ID: 7, Name: "pen", Price: 12.5})
- require.NoError(t, err)
- t.Log(got)
- assert.JSONEq(t, `{
- "price": 12.5,
- "name": "pen",
- "id": 7
- }`, got)
- }
執行
go test -v .,輸出:- === RUN TestEncode
- api_test.go:13: {"id":7,"name":"pen","price":12.5}
- --- PASS: TestEncode (0.00s)
- PASS
- ok example.com/api 0.239s
預期值的 key 順序與縮排都和實際輸出不同,仍然通過。
注意:任一邊不是合法 JSON 時,
JSONEq 直接判定失敗。Eventually:等待非同步結果
背景 goroutine 做完事情的時間不固定,寫死
time.Sleep 不是太久就是不夠。Eventually 每隔 tick 呼叫一次 condition,在 waitFor 內只要有一次回傳 true 就通過,逾時才失敗。簽名:
- func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool
被測檔
worker.go:- package worker
- import (
- "sync/atomic"
- "time"
- )
- type Worker struct {
- done atomic.Bool
- }
- func (w *Worker) Start() {
- go func() {
- time.Sleep(50 * time.Millisecond)
- w.done.Store(true)
- }()
- }
- func (w *Worker) Done() bool {
- return w.done.Load()
- }
測試檔
worker_test.go:- package worker
- import (
- "testing"
- "time"
- "github.com/stretchr/testify/assert"
- )
- func TestWorkerFinishes(t *testing.T) {
- w := &Worker{}
- w.Start()
- assert.False(t, w.Done())
- assert.Eventually(t, w.Done, time.Second, 10*time.Millisecond)
- }
執行
go test -v .,輸出:- === RUN TestWorkerFinishes
- --- PASS: TestWorkerFinishes (0.06s)
- PASS
- ok example.com/worker 0.298s
約 50ms 後條件成立,測試通過,不必等滿 1 秒。耗時數字因機器而異。
注意:
condition 會在另一個 goroutine 被呼叫,讀取共享狀態要用 原子操作 或鎖,否則 go test -race 會回報競態條件。suite:測試套組
SetupTest 與 TearDownTest
一組測試都需要同樣的準備(建立物件、開暫存目錄)時,可以用
suite 把它們放進同一個結構體:- 定義結構體並嵌入
suite.Suite(見嵌入與組合) - 以
Test開頭的方法就是一個子測試 - 用一個普通的
TestXxx呼叫suite.Run啟動整組
可選的掛鉤(hook)方法:
| 方法 | 執行時機 |
|---|---|
SetupSuite | 整組開始前一次 |
SetupTest | 每個測試方法之前 |
TearDownTest | 每個測試方法之後 |
TearDownSuite | 整組結束後一次 |
嵌入的
suite.Suite 已經帶有所有 assert 斷言(s.Equal(...)),s.Require() 取得 require 版本,s.T() 取得目前的 *testing.T。簽名:
- func Run(t *testing.T, suite TestingSuite)
被測檔
cart.go:- package cart
- type Cart struct {
- items map[string]int
- }
- func New() *Cart {
- return &Cart{items: map[string]int{}}
- }
- func (c *Cart) Add(sku string, qty int) {
- c.items[sku] += qty
- }
- func (c *Cart) Count() int {
- n := 0
- for _, q := range c.items {
- n += q
- }
- return n
- }
測試檔
cart_test.go:- package cart
- import (
- "testing"
- "github.com/stretchr/testify/suite"
- )
- type CartSuite struct {
- suite.Suite
- cart *Cart
- }
- func (s *CartSuite) SetupSuite() {
- s.T().Log("SetupSuite")
- }
- func (s *CartSuite) SetupTest() {
- s.T().Log("SetupTest")
- s.cart = New()
- }
- func (s *CartSuite) TearDownTest() {
- s.T().Log("TearDownTest")
- }
- func (s *CartSuite) TestAdd() {
- s.cart.Add("pen", 2)
- s.Equal(2, s.cart.Count())
- }
- func (s *CartSuite) TestAddSameSKU() {
- s.cart.Add("pen", 1)
- s.cart.Add("pen", 3)
- s.Require().Equal(4, s.cart.Count())
- }
- func TestCartSuite(t *testing.T) {
- suite.Run(t, new(CartSuite))
- }
執行
go test -v .,輸出:- === RUN TestCartSuite
- cart_test.go:15: SetupSuite
- === RUN TestCartSuite/TestAdd
- cart_test.go:19: SetupTest
- cart_test.go:24: TearDownTest
- === RUN TestCartSuite/TestAddSameSKU
- cart_test.go:19: SetupTest
- cart_test.go:24: TearDownTest
- --- PASS: TestCartSuite (0.00s)
- --- PASS: TestCartSuite/TestAdd (0.00s)
- --- PASS: TestCartSuite/TestAddSameSKU (0.00s)
- PASS
- ok example.com/cart 0.265s
每個測試方法前都重新
New() 一台購物車,所以 TestAddSameSKU 不會看到 TestAdd 加進去的 2 支筆。注意:suite 的測試方法預設依序執行,不支援
t.Parallel()。需要平行執行的測試用一般的表格驅動測試寫法。mock:模擬相依物件
mock.Mock 基本用法
被測程式依賴一個介面(例如寄信服務)時,測試不想真的寄信,可以寫一個實作該介面的假物件。
mock.Mock 幫這個假物件記錄「被怎麼呼叫」與「該回傳什麼」:| 步驟 | API |
|---|---|
| 在假方法內回報呼叫並取回設定的回傳值 | args := m.Called(參數...),再用 args.Error(0)、args.Int(0)、args.Get(0) 取值 |
| 設定期望:哪個方法、什麼參數、回傳什麼 | m.On("方法名", 參數...).Return(回傳值...) |
| 限制次數 | .Once()、.Twice()、.Times(n) |
| 不在意某個參數 | mock.Anything |
| 測試最後確認期望都發生 | m.AssertExpectations(t) |
被測檔
alert.go:- package alert
- import "fmt"
- type Notifier interface {
- Send(to, msg string) error
- }
- func Broadcast(n Notifier, users []string, msg string) error {
- for _, u := range users {
- if err := n.Send(u, msg); err != nil {
- return fmt.Errorf("send to %s: %w", u, err)
- }
- }
- return nil
- }
測試檔
alert_test.go:- package alert
- import (
- "errors"
- "testing"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/mock"
- )
- type MockNotifier struct {
- mock.Mock
- }
- func (m *MockNotifier) Send(to, msg string) error {
- args := m.Called(to, msg)
- return args.Error(0)
- }
- func TestBroadcast(t *testing.T) {
- n := new(MockNotifier)
- n.On("Send", "alice", "deploy done").Return(nil).Once()
- n.On("Send", "bob", mock.Anything).Return(nil).Once()
- err := Broadcast(n, []string{"alice", "bob"}, "deploy done")
- assert.NoError(t, err)
- n.AssertExpectations(t)
- n.AssertNumberOfCalls(t, "Send", 2)
- }
- func TestBroadcastStopsOnError(t *testing.T) {
- n := new(MockNotifier)
- n.On("Send", "alice", mock.Anything).Return(errors.New("smtp down"))
- err := Broadcast(n, []string{"alice", "bob"}, "hi")
- assert.EqualError(t, err, "send to alice: smtp down")
- n.AssertNotCalled(t, "Send", "bob", mock.Anything)
- }
執行
go test -v .,輸出:- === RUN TestBroadcast
- --- PASS: TestBroadcast (0.00s)
- === RUN TestBroadcastStopsOnError
- --- PASS: TestBroadcastStopsOnError (0.00s)
- PASS
- ok example.com/alert 0.244s
第二個測試讓
alice 寄送失敗,再用 AssertNotCalled 確認 Broadcast 遇到錯誤就停下、沒有寄給 bob。注意:假物件被呼叫時,如果找不到符合參數的
On 設定,Called 會 panic 並列出最接近的設定;先呼叫 n.Test(t) 則改成讓該測試失敗。MockNotifier 這類樣板程式碼也可以交給 mockery 之類的工具產生;想要從介面自動產生、並在編譯期檢查方法名稱,可以改用 gomock。重點整理
- testify 最新主版本仍是 v1,以
go get github.com/stretchr/testify@v1.12.1安裝,import 路徑沒有/v2 assert失敗後繼續、require失敗即停;後續程式依賴的前置條件用require- 斷言參數順序是
(t, 預期值, 實際值);Equal會比較型別並在失敗時附 diff - 錯誤用
NoError/ErrorIs,JSON 用JSONEq,非同步結果用Eventually取代time.Sleep suite以SetupTest/TearDownTest讓每個測試方法從乾淨狀態開始mock.Mock以On(...).Return(...)設定期望,最後用AssertExpectations確認都發生