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.DeepEqualassert.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 寫法混用。

安裝


  1. go get github.com/stretchr/testify@v1.12.1

testify 的最新主版本仍是 v1,import 路徑沒有 /v2。官方 README 說明 v1 會持續維護、不接受破壞性變更,所以照著 github.com/stretchr/testify/... 匯入即可。
本頁每個範例都是一個獨立的模組,go.mod 長這樣(模組名稱依範例而不同):
  1. module example.com/calc
  2. go 1.26
  3. require github.com/stretchr/testify v1.12.1

assert 與 require


testify 有兩個斷言套件,函式名稱與參數完全相同,差別只在「失敗後要不要繼續」:
套件失敗時呼叫失敗後適合
assertt.Errorf繼續執行,函式回傳 false彼此獨立的多個檢查
requiret.FailNow立刻結束這個測試後面的程式依賴這個結果(例如 err 不為 nil 時指標是 nil)

所有斷言的參數順序都是 (t, 預期值, 實際值, 額外訊息...),預期值在前。

assert:失敗後繼續


被測檔 calc.go:
  1. package calc
  2. import "errors"
  3. var ErrDivByZero = errors.New("division by zero")
  4. func Divide(a, b int) (int, error) {
  5. if b == 0 {
  6. return 0, ErrDivByZero
  7. }
  8. return a / b, nil
  9. }

測試檔 calc_test.go(故意用除以 0 製造失敗):
  1. package calc
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. )
  6. func TestDivide(t *testing.T) {
  7. got, err := Divide(10, 0)
  8. assert.NoError(t, err)
  9. assert.Equal(t, 5, got)
  10. t.Log("still running")
  11. }

執行:
  1. go test -v .

輸出:
  1. === RUN TestDivide
  2. calc_test.go:11:
  3. Error Trace: .../calc/calc_test.go:11
  4. Error: Received unexpected error:
  5. division by zero
  6. Test: TestDivide
  7. calc_test.go:12:
  8. Error Trace: .../calc/calc_test.go:12
  9. Error: Not equal:
  10. expected: 5
  11. actual : 0
  12. Test: TestDivide
  13. calc_test.go:13: still running
  14. --- FAIL: TestDivide (0.00s)
  15. FAIL
  16. FAIL example.com/calc 0.225s
  17. FAIL

兩個斷言都失敗,而且最後的 t.Log 仍有執行。Error Trace 實際會印出檔案的完整路徑,這裡以 ... 省略前段;最後一欄的耗時數字因機器而異。

require:失敗就停


被測檔 user.go:找不到使用者時回傳 nil 指標與錯誤。
  1. package user
  2. import "errors"
  3. var ErrNotFound = errors.New("user not found")
  4. type User struct {
  5. ID int
  6. Name string
  7. }
  8. var users = map[int]*User{1: {ID: 1, Name: "Alice"}}
  9. func Find(id int) (*User, error) {
  10. u, ok := users[id]
  11. if !ok {
  12. return nil, ErrNotFound
  13. }
  14. return u, nil
  15. }

測試檔 user_test.go:
  1. package user
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. "github.com/stretchr/testify/require"
  6. )
  7. func TestFind(t *testing.T) {
  8. u, err := Find(2)
  9. require.NoError(t, err)
  10. assert.Equal(t, "Alice", u.Name)
  11. }

執行 go test -v .,輸出:
  1. === RUN TestFind
  2. user_test.go:12:
  3. Error Trace: .../user/user_test.go:12
  4. Error: Received unexpected error:
  5. user not found
  6. Test: TestFind
  7. --- FAIL: TestFind (0.00s)
  8. FAIL
  9. FAIL example.com/user 0.241s
  10. FAIL

require.NoError 失敗後測試立即結束,u.Name 那行沒有執行。
注意:如果這裡改用 assert.NoError,程式會繼續執行到 u.Name,而 u 是 nil,測試會因為 nil 指標而 panic。檢查錯誤、檢查長度這類「後面要靠它」的前置條件用 require,其餘用 assert。

常用斷言


以下斷言 assert 與 require 都有,簽名相同(require 版沒有回傳值)。

Equal:比對任意值


Equal 用 ObjectsAreEqual 深度比對,結構體、切片、映射都能直接比;失敗時附上逐欄位的 diff。
簽名:
  1. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool

被測檔 profile.go:
  1. package profile
  2. import "strings"
  3. type Profile struct {
  4. Name string
  5. Email string
  6. Tags []string
  7. }
  8. func Normalize(p Profile) Profile {
  9. p.Name = strings.TrimSpace(p.Name)
  10. p.Email = strings.ToLower(p.Email)
  11. return p
  12. }

測試檔 profile_test.go(預期值故意多一個 tag,示範失敗時的 diff):
  1. package profile
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. )
  6. func TestNormalize(t *testing.T) {
  7. got := Normalize(Profile{Name: " Bob ", Email: "Bob@Example.COM", Tags: []string{"go"}})
  8. want := Profile{Name: "Bob", Email: "bob@example.com", Tags: []string{"go", "admin"}}
  9. assert.Equal(t, want, got)
  10. }

執行 go test -v .,輸出:
  1. === RUN TestNormalize
  2. profile_test.go:12:
  3. Error Trace: .../profile/profile_test.go:12
  4. Error: Not equal:
  5. expected: profile.Profile{Name:"Bob", Email:"bob@example.com", Tags:[]string{"go", "admin"}}
  6. actual : profile.Profile{Name:"Bob", Email:"bob@example.com", Tags:[]string{"go"}}
  7. Diff:
  8. --- Expected
  9. +++ Actual
  10. @@ -3,5 +3,4 @@
  11. Email: (string) (len=15) "bob@example.com",
  12. - Tags: ([]string) (len=2) {
  13. - (string) (len=2) "go",
  14. - (string) (len=5) "admin"
  15. + Tags: ([]string) (len=1) {
  16. + (string) (len=2) "go"
  17. }
  18. Test: TestNormalize
  19. --- FAIL: TestNormalize (0.00s)
  20. FAIL
  21. FAIL example.com/profile 0.236s
  22. FAIL

- 開頭是預期值、+ 開頭是實際值,一眼看出差在 Tags。
注意:Equal 會比較型別,int(5) 與 int64(5) 不相等。

NoError 與 ErrorIs:檢查錯誤


  • NoError(t, err):err 必須是 nil
  • ErrorIs(t, err, target):等同 errors.Is(err, target),能穿透 %w 包裝的錯誤鏈(見錯誤包裝)
  • EqualError(t, err, "..."):比對 err.Error() 的完整字串

簽名:
  1. func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool
  2. func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool

被測檔 config.go:
  1. package config
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  6. )
  7. var ErrMissing = errors.New("missing key")
  8. func Port(env map[string]string) (int, error) {
  9. v, ok := env["PORT"]
  10. if !ok {
  11. return 0, fmt.Errorf("config PORT: %w", ErrMissing)
  12. }
  13. return strconv.Atoi(v)
  14. }

測試檔 config_test.go:
  1. package config
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. )
  6. func TestPortOK(t *testing.T) {
  7. p, err := Port(map[string]string{"PORT": "8080"})
  8. assert.NoError(t, err)
  9. assert.Equal(t, 8080, p)
  10. }
  11. func TestPortMissing(t *testing.T) {
  12. _, err := Port(map[string]string{})
  13. assert.ErrorIs(t, err, ErrMissing)
  14. assert.EqualError(t, err, "config PORT: missing key")
  15. }

執行 go test -v .,輸出:
  1. === RUN TestPortOK
  2. --- PASS: TestPortOK (0.00s)
  3. === RUN TestPortMissing
  4. --- PASS: TestPortMissing (0.00s)
  5. PASS
  6. ok example.com/config 0.238s

判斷「是哪一種錯誤」優先用 ErrorIs;錯誤訊息字串之後可能改寫,EqualError 只在訊息本身就是規格時使用。

Contains 與 Len:檢查集合


  • Contains(t, s, x):字串含子字串、切片含元素、映射含 key
  • NotContains:相反
  • Len(t, obj, n):字串、切片、映射、channel 的長度為 n

簽名:
  1. func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
  2. func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool

被測檔 words.go:
  1. package words
  2. import "strings"
  3. func Count(text string) map[string]int {
  4. m := map[string]int{}
  5. for _, w := range strings.Fields(strings.ToLower(text)) {
  6. m[w]++
  7. }
  8. return m
  9. }
  10. func Unique(text string) []string {
  11. var out []string
  12. seen := map[string]bool{}
  13. for _, w := range strings.Fields(strings.ToLower(text)) {
  14. if !seen[w] {
  15. seen[w] = true
  16. out = append(out, w)
  17. }
  18. }
  19. return out
  20. }

測試檔 words_test.go:
  1. package words
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. )
  6. func TestUnique(t *testing.T) {
  7. got := Unique("Go is fun and go is fast")
  8. assert.Len(t, got, 5)
  9. assert.Contains(t, got, "fun")
  10. assert.NotContains(t, got, "Go")
  11. }
  12. func TestCount(t *testing.T) {
  13. got := Count("a b a")
  14. assert.Len(t, got, 2)
  15. assert.Contains(t, got, "a")
  16. assert.Contains(t, "hello, gopher", "gopher")
  17. }

執行 go test -v .,輸出:
  1. === RUN TestUnique
  2. --- PASS: TestUnique (0.00s)
  3. === RUN TestCount
  4. --- PASS: TestCount (0.00s)
  5. PASS
  6. ok example.com/words 0.242s

Contains 用在映射時只檢查 key,不看 value。

JSONEq:比對 JSON 內容


直接比 JSON 字串會被 key 順序與空白影響。JSONEq 先把兩邊解析成資料再比較,只看內容是否相同。
簽名:
  1. func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool

被測檔 api.go:
  1. package api
  2. import "encoding/json"
  3. type Item struct {
  4. ID int `json:"id"`
  5. Name string `json:"name"`
  6. Price float64 `json:"price"`
  7. }
  8. func Encode(it Item) (string, error) {
  9. b, err := json.Marshal(it)
  10. return string(b), err
  11. }

測試檔 api_test.go:
  1. package api
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. "github.com/stretchr/testify/require"
  6. )
  7. func TestEncode(t *testing.T) {
  8. got, err := Encode(Item{ID: 7, Name: "pen", Price: 12.5})
  9. require.NoError(t, err)
  10. t.Log(got)
  11. assert.JSONEq(t, `{
  12. "price": 12.5,
  13. "name": "pen",
  14. "id": 7
  15. }`, got)
  16. }

執行 go test -v .,輸出:
  1. === RUN TestEncode
  2. api_test.go:13: {"id":7,"name":"pen","price":12.5}
  3. --- PASS: TestEncode (0.00s)
  4. PASS
  5. ok example.com/api 0.239s

預期值的 key 順序與縮排都和實際輸出不同,仍然通過。
注意:任一邊不是合法 JSON 時,JSONEq 直接判定失敗。

Eventually:等待非同步結果


背景 goroutine 做完事情的時間不固定,寫死 time.Sleep 不是太久就是不夠。Eventually 每隔 tick 呼叫一次 condition,在 waitFor 內只要有一次回傳 true 就通過,逾時才失敗。
簽名:
  1. func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool

被測檔 worker.go:
  1. package worker
  2. import (
  3. "sync/atomic"
  4. "time"
  5. )
  6. type Worker struct {
  7. done atomic.Bool
  8. }
  9. func (w *Worker) Start() {
  10. go func() {
  11. time.Sleep(50 * time.Millisecond)
  12. w.done.Store(true)
  13. }()
  14. }
  15. func (w *Worker) Done() bool {
  16. return w.done.Load()
  17. }

測試檔 worker_test.go:
  1. package worker
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestWorkerFinishes(t *testing.T) {
  8. w := &Worker{}
  9. w.Start()
  10. assert.False(t, w.Done())
  11. assert.Eventually(t, w.Done, time.Second, 10*time.Millisecond)
  12. }

執行 go test -v .,輸出:
  1. === RUN TestWorkerFinishes
  2. --- PASS: TestWorkerFinishes (0.06s)
  3. PASS
  4. ok example.com/worker 0.298s

約 50ms 後條件成立,測試通過,不必等滿 1 秒。耗時數字因機器而異。
注意:condition 會在另一個 goroutine 被呼叫,讀取共享狀態要用 原子操作 或鎖,否則 go test -race 會回報競態條件。

suite:測試套組


SetupTest 與 TearDownTest


一組測試都需要同樣的準備(建立物件、開暫存目錄)時,可以用 suite 把它們放進同一個結構體:
  1. 定義結構體並嵌入 suite.Suite(見嵌入與組合)
  2. 以 Test 開頭的方法就是一個子測試
  3. 用一個普通的 TestXxx 呼叫 suite.Run 啟動整組

可選的掛鉤(hook)方法:
方法執行時機
SetupSuite整組開始前一次
SetupTest每個測試方法之前
TearDownTest每個測試方法之後
TearDownSuite整組結束後一次

嵌入的 suite.Suite 已經帶有所有 assert 斷言(s.Equal(...)),s.Require() 取得 require 版本,s.T() 取得目前的 *testing.T。
簽名:
  1. func Run(t *testing.T, suite TestingSuite)

被測檔 cart.go:
  1. package cart
  2. type Cart struct {
  3. items map[string]int
  4. }
  5. func New() *Cart {
  6. return &Cart{items: map[string]int{}}
  7. }
  8. func (c *Cart) Add(sku string, qty int) {
  9. c.items[sku] += qty
  10. }
  11. func (c *Cart) Count() int {
  12. n := 0
  13. for _, q := range c.items {
  14. n += q
  15. }
  16. return n
  17. }

測試檔 cart_test.go:
  1. package cart
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/suite"
  5. )
  6. type CartSuite struct {
  7. suite.Suite
  8. cart *Cart
  9. }
  10. func (s *CartSuite) SetupSuite() {
  11. s.T().Log("SetupSuite")
  12. }
  13. func (s *CartSuite) SetupTest() {
  14. s.T().Log("SetupTest")
  15. s.cart = New()
  16. }
  17. func (s *CartSuite) TearDownTest() {
  18. s.T().Log("TearDownTest")
  19. }
  20. func (s *CartSuite) TestAdd() {
  21. s.cart.Add("pen", 2)
  22. s.Equal(2, s.cart.Count())
  23. }
  24. func (s *CartSuite) TestAddSameSKU() {
  25. s.cart.Add("pen", 1)
  26. s.cart.Add("pen", 3)
  27. s.Require().Equal(4, s.cart.Count())
  28. }
  29. func TestCartSuite(t *testing.T) {
  30. suite.Run(t, new(CartSuite))
  31. }

執行 go test -v .,輸出:
  1. === RUN TestCartSuite
  2. cart_test.go:15: SetupSuite
  3. === RUN TestCartSuite/TestAdd
  4. cart_test.go:19: SetupTest
  5. cart_test.go:24: TearDownTest
  6. === RUN TestCartSuite/TestAddSameSKU
  7. cart_test.go:19: SetupTest
  8. cart_test.go:24: TearDownTest
  9. --- PASS: TestCartSuite (0.00s)
  10. --- PASS: TestCartSuite/TestAdd (0.00s)
  11. --- PASS: TestCartSuite/TestAddSameSKU (0.00s)
  12. PASS
  13. 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:
  1. package alert
  2. import "fmt"
  3. type Notifier interface {
  4. Send(to, msg string) error
  5. }
  6. func Broadcast(n Notifier, users []string, msg string) error {
  7. for _, u := range users {
  8. if err := n.Send(u, msg); err != nil {
  9. return fmt.Errorf("send to %s: %w", u, err)
  10. }
  11. }
  12. return nil
  13. }

測試檔 alert_test.go:
  1. package alert
  2. import (
  3. "errors"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/stretchr/testify/mock"
  7. )
  8. type MockNotifier struct {
  9. mock.Mock
  10. }
  11. func (m *MockNotifier) Send(to, msg string) error {
  12. args := m.Called(to, msg)
  13. return args.Error(0)
  14. }
  15. func TestBroadcast(t *testing.T) {
  16. n := new(MockNotifier)
  17. n.On("Send", "alice", "deploy done").Return(nil).Once()
  18. n.On("Send", "bob", mock.Anything).Return(nil).Once()
  19. err := Broadcast(n, []string{"alice", "bob"}, "deploy done")
  20. assert.NoError(t, err)
  21. n.AssertExpectations(t)
  22. n.AssertNumberOfCalls(t, "Send", 2)
  23. }
  24. func TestBroadcastStopsOnError(t *testing.T) {
  25. n := new(MockNotifier)
  26. n.On("Send", "alice", mock.Anything).Return(errors.New("smtp down"))
  27. err := Broadcast(n, []string{"alice", "bob"}, "hi")
  28. assert.EqualError(t, err, "send to alice: smtp down")
  29. n.AssertNotCalled(t, "Send", "bob", mock.Anything)
  30. }

執行 go test -v .,輸出:
  1. === RUN TestBroadcast
  2. --- PASS: TestBroadcast (0.00s)
  3. === RUN TestBroadcastStopsOnError
  4. --- PASS: TestBroadcastStopsOnError (0.00s)
  5. PASS
  6. 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 確認都發生

資料來源