使用 Testify 為 Go 專案進行單元測試

前言

Go 的 testing 標準庫內建單元測試方法,不過 testify 套件進一步封裝,並提供許多方便的斷言方法。

以下以 LeetCode 第 1 題 Two Sum 為例,建立一些測試案例,並進行單元測試。

做法

下載 Testify 套件。

1
go get github.com/stretchr/testify

新增 main.go 檔:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

func twoSum(nums []int, target int) []int {
index := make(map[int]int, len(nums))

for i, num := range nums {
if j, ok := index[target-num]; ok == true {
return []int{j, i}
}
index[num] = i
}

return []int{}
}

新增 main_test.go 檔,並建立測試案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main

import (
"testing"

"github.com/stretchr/testify/assert"
)

// 測試案例
type question struct {
p parameter
a answer
}

// 參數
type parameter struct {
first []int
second int
}

// 答案
type answer struct {
first []int
}

func TestProblem(t *testing.T) {
questions := []question{
question{
p: parameter{
first: []int{2, 7, 11, 15},
second: 9,
},
a: answer{
first: []int{0, 1},
},
},
question{
p: parameter{
first: []int{2, 7, 11, 15},
second: 8,
},
a: answer{
first: []int{},
},
},
}

for _, q := range questions {
a, p := q.a, q.p
assert.Equal(t, a.first, twoSum(p.first, p.second))
}
}

執行測試:

1
go test ./...
  • 路徑 ./... 代表所有子資料夾下的測試都會被執行。