-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_test.go
100 lines (91 loc) · 1.62 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"fmt"
"os"
"testing"
)
func TestAbs(t *testing.T) {
teardownTest := setupTest(t)
defer teardownTest(t)
want := 1
if got := Abs(-1); got != want {
t.Fatalf("Abs() = %v, want %v", got, want)
}
}
func TestAbsWithTable(t *testing.T) {
type args struct {
x int
}
tests := []struct {
name string
args args
want int
}{
{
name: "positive",
args: args{x: 1},
want: 1,
},
{
name: "negative",
args: args{x: -1},
want: 1,
},
}
for _, tt := range tests {
teardownTest := setupTest(t)
defer teardownTest(t) // 错误写法,defer 语句不会在本轮 for 循环结束时被执行
if got := Abs(tt.args.x); got != tt.want {
t.Fatalf("Abs() = %v, want %v", got, tt.want)
}
}
}
func TestAbsWithTableAndSubtests(t *testing.T) {
type args struct {
x int
}
tests := []struct {
name string
args args
want int
}{
{
name: "positive",
args: args{x: 1},
want: 1,
},
{
name: "negative",
args: args{x: -1},
want: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
teardownTest := setupTest(t)
defer teardownTest(t)
if got := Abs(tt.args.x); got != tt.want {
t.Fatalf("Abs() = %v, want %v", got, tt.want)
}
})
}
}
// testing.TB is the interface common to T, B, and F.
func setupTest(tb testing.TB) func(tb testing.TB) {
fmt.Println(">> setup Test")
return func(tb testing.TB) {
fmt.Println(">> teardown Test")
}
}
func setup() {
fmt.Println("> setup completed")
}
func teardown() {
fmt.Println("> teardown completed")
}
func TestMain(m *testing.M) {
setup()
code := m.Run()
teardown()
os.Exit(code)
}