-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtesting.go
66 lines (58 loc) · 1.62 KB
/
testing.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
//
// gobyexample.com
// Testing
// testing.go
//
package main
import (
"fmt"
"testing"
)
// We’ll be testing this simple implementation of an
// integer minimum. Typically, the code we’re testing
// would be in a source file named something like intutils.go,
// and the test file for it would then be named intutils_test.go.
func IntMin(a, b int) int {
if a < b {
return a
}
return b
}
// A test is created by writing a function with a name
// beginning with Test.
func TestIntMinBasic(t *testing.T) {
ans := IntMin(2, -2)
if ans != -2 {
// t.Error* will report test failures but continue
// executing the test. t.Fatal* will report test
// failures and stop the test immediately.
t.Errorf("IntMin(2, -2) = %d; want -2", ans)
}
}
// Writing tests can be repetitive, so it’s idiomatic to use
// a table-driven style, where test inputs and expected outputs
// are listed in a table and a single loop walks over them and
// performs the test logic.
func TestIntMinTableDriven(t *testing.T) {
var tests = []struct {
a, b int
want int
}{
{0, 1, 0},
{1, 0, 0},
{2, -2, -2},
{0, -1, -1},
{-1, 0, -1},
}
// t.Run enables running “subtests”, one for each table entry.
// These are shown separately when executing go test -v.
for _, tt := range tests {
testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
t.Run(testname, func(t *testing.T) {
ans := IntMin(tt.a, tt.b)
if ans != tt.want {
t.Errorf("got %d, want %d", ans, tt.want)
}
})
}
}