Go测试

5/21/2021 gogotext

# go test工具

go test用于编译单元测试,检测方法函数是否有问题,熟悉下相关参数,可以让测试过程更新快捷

  • 直接运行编译整个项目的测试文件
go test
1
  • 测试单个测试文件,被测文件和对应单元测试成对出现,顺序可调换

    go test math.go math_test.go
    
    1
  • 查看详细结果

    go test -v
    
    1
  • 只测试某个函数,或者某几个函数,-run支持正则,如只测试 TestAddMore,TestAddMoreAndMore

    go test -v -run="TestAddMore"
    
    1
  • 生成test的二进制文件,加 -c 参数

    go test -c 
    
    1
  • 执行这个text测试文件,加 -o 参数

    go test -v -o math.test.exe
    
    1
  • 查看覆盖率,加 -cover 参数

    go test -v -cover math.go math_test.go
    
    1

# go单元测试

创建一个math.go,写一个add的Func函数,如下

package main

func Add(x, y int) int {
	return x + y
}
1
2
3
4
5

同级建立一个math_test.go的测试文件

package Test

import "testing"

type TestTable struct {
	xArg int
	yArg int
}

// 简单测试,单元测试
func TestAdd(t *testing.T) {
	t.Log(Add(1, 2))
}

// 少量样例测试,表组测试
func TestAddMore(t *testing.T) {
	sum := Add(1, 2)
	if sum == 3 {
		t.Log("the result is ok")
	} else {
		t.Fatal("the result is wrong")
	}

	sum = Add(2, 4)
	if sum == 6 {
		t.Log("the result is ok")
	} else {
		t.Fatal("the result is wrong")
	}
}

// 大量测试样例,表格测试法
func TestAddMoreAndMore(t *testing.T) {
	tables := []TestTable{
		{1, 2},
		{2, 4},
		{4, 8},
		{5, 10},
		{6, 12},
	}

	for _, table := range tables {
		result := Add(table.xArg, table.yArg)
		if result == (table.xArg + table.yArg) {
			t.Log("the result is ok")
		} else {
			t.Fatal("the result is wrong")
		}
	}
}
// === RUN   TestAdd
// math_test.go:12: 3
// --- PASS: TestAdd (0.00s)
// === RUN   TestAddMore
// math_test.go:19: the result is ok
// math_test.go:26: the result is ok
// --- PASS: TestAddMore (0.00s)
// === RUN   TestAddMoreAndMore
// math_test.go:45: the result is ok
// math_test.go:45: the result is ok
// math_test.go:45: the result is ok
// math_test.go:45: the result is ok
// math_test.go:45: the result is ok
// --- PASS: TestAddMoreAndMore (0.00s)
// PASS
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

# go单元测试编写原则

  • 单元测试以_test.go结尾,最好就是 被测试文件_test.go
  • 单元测试函数名必须以 Test开口,如TestAdd
  • 单元测试函数接口一个指向 testing.T 类型的指针,而且不返回任何值

# go mock工具

参考 (opens new window),未尝试

# 练习源码

Test (opens new window)