testing - 单元测试

testing 为GO语言package 提供自动化测试的支持

1
func TestXxx(*testing.T)

示例

要测试的代码:

1
2
3
4
5
6
func Fib(n int) int {
if n < 2 {
return n
}
return Fib(n-1) + Fib(n-1)
}

测试代码:

1
2
3
4
5
6
7
8
9
10
func TestFib(t *testing.T) {
var (
in = 7
expected = 13
)
actual := Fib(in)
if actual != expected {
t.Errorf("Fib(%d) = %d; expected %d", in, actual, expected)
}
}
1
2
3
4
5
$ go test .
--- FAIL: TestSum (0.00s)
t_test.go:16: Fib(10) = 64; expected 13
FAIL
FAIL chapter09/testing 0.009s

Table-Driven Test

case 覆盖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func TestFib(t *testing.T) {
var fibTests = []struct {
in int // input
expected int // expected result
}{
{1, 1},
{2, 1},
{3, 2},
{4, 3},
{5, 5},
{6, 8},
{7, 13},
}

for _, tt := range fibTests {
actual := Fib(tt.in)
if actual != tt.expected {
t.Errorf("Fib(%d) = %d; expected %d", tt.in, actual, tt.expected)
}
}
}

Copyright © Ywnline 版权所有 冀ICP备20005992号-1