go语言 单元测试

62 阅读2分钟

单元测试

Go本身提供了一套轻量级的测试框架。符合规则的测试代码会在运行测试时被自动识别并执行。单元测试源文件的命名规则如下:在需要测试的包下面创建以“_test”结尾的go文件,形如**,_test.go。

Go的单元测试函数分为两类:功能测试函数和性能测试函数,分别为以TestBenchmark为函数名前缀并以*testing.T为单一参数的函数。下面是测试函数声明的例子:

func TestAdd1(t *testing.T) 
func BenchmarkAdd1(t *testing.T) 

测试工具会根据函数中的实际执行动作得到不同的测试结果。功能测试函数会根据测试代码执行过程中是否发生错误来返回不同的结果,而性能测试函数仅仅打印整个测试过程的花费时间。

一个例子

example/
|–calc.go
|–calc_test.go
假如 calc.go 的代码如下:

package main

func Add(a int, b int) int {
    return a + b
}

func Mul(a int, b int) int {
    return a * b
}

那么 calc_test.go 中的测试用例可以这么写:

package main

import "testing"

func TestAdd(t *testing.T) {
	if ans := Add(1, 2); ans != 3 {
		t.Errorf("1 + 2 expected be 3, but %d got", ans)
	}

	if ans := Add(-10, -20); ans != -30 {
		t.Errorf("-10 + -20 expected be -30, but %d got", ans)
	}
}

测试用例名称一般命名为 Test 加上待测试的方法名。测试用的参数有且只有一个,在这里是 t *testing.T。
基准测试(benchmark)的参数是 *testing.B,TestMain 的参数是 *testing.M 类型。
运行 go test,该 package 下所有的测试用例都会被执行。

$ go test
ok example 0.009s
或 go test -v,-v 参数会显示每个用例的测试结果,另外 -cover 参数可以查看覆盖率。

$ go test -v
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
=== RUN   TestMul
--- PASS: TestMul (0.00s)
PASS
ok      example 0.007s

如果只想运行其中的一个用例,例如 TestAdd,可以用 -run 参数指定,该参数支持通配符 *,和部分正则表达式,例如 ^、$。

$ go test -run TestAdd -v
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
PASS
ok      example 0.007s