Go语言内建testing
包,我们可以简单地通过导入测试包
、约定命名
和ge test
快速完成单元测试的编写和执行。
注意:go test
需要在Go模块下才能正常运行,否则会报下面这段错误:
go: go.mod file not found in current directory or any parent directory; see 'go help modules
不了解Go模块的,可以先看这篇文章 Go语言中的模块
下面我们测试testing_ane_benchmarking.go
中main
包下的IntMin
函数。
testing_ane_benchmarking.go
文件具体内容如下:
package main
func IntMin(a, b int) int {
if a < b {
return a
}
return b
}
- 创建测试文件
我们需要创建一个名字以被测试文件名(不含.go)为前缀,_test.go
为后缀的文件,go test
会自动寻找并执行遵循这类约定命名规则的文件。
如果go test
没有找到这类文件,就会报[no test files]
错误。
这里我们将测试文件命名为testing_ane_benchmarking_test.go
。
- 创建一个简单的测试样例测试函数是否正常运行。
测试包提供两类错误输出函数:Error
和Fatal
,Error
会报告测试错误并继续运行,而Fatal
会报告测试错误并终止测试。它们都提供对应的格式化输出Errorf
和Fatalf
。下面使用Errorf
做一个简单测试。
测试需要编写一个以Test
为前缀且没有任何返回值的函数,go test
会自动运行遵守这种命名规则的函数。
package main
import (
// 导入测试包
"testing"
)
// 测试基本功能
func IntMinBasic(t *testing.T) {
ans := IntMin(2, -2)
if ans != -2 {
// 错误格式化输出
t.Errorf("IntMin(2, -2) = %d; want -2", ans)
}
}
- 测试覆盖率
在Go中,我们可以使用go test -cover
来运行覆盖率分析,使用go test -coverprofile
将覆盖率分析报告输出到文件中,如:
go test -coverprofile=c.out
上面命令会将报告输出到c.out
文件中。
我们还可以用
go tool cover -html=c.out
打开一个网页显示详细的覆盖率报告,查看每一行代码是否被测试覆盖。
- 编写基准测试
基准测试同样需要写在以_test.go
为后缀的文件中,函数名以Benchmark
为前缀,运行go test -bench=.
执行所有基准测试,如果只想运行特定基准测试则执行go test -bench=funcname
package main
import (
// 导入测试包
"testing"
)
// 单元测试代码
// ...
// 基准测试
func BenchmarkIntMin(b *testing.B) {
// 测试器会多次执行基准测试函数,每次执行都会增加b.N,直到收集到精确的测量值。
for i := 0; i < b.N; i++ {
IntMin(1, 2)
}
}
执行基准测试
go test -bench=.
测试结果
# 操作系统信息:macOS
goos: darwin
# 架构:arm64
goarch: arm64
# 基准测试运行所在的包
pkg: example.com/testing_and_benchmarking
# 基准测试名称:函数名BenchmarkIntMin,最大并发CPU为8
BenchmarkIntMin-8
# 基准测试运行次数(也就是b.N的值):1000000000次;每次运行的平均时间:0.3175纳秒
1000000000 0.3175 ns/op
# 测试通过:包名 + 测试总时间
PASS
ok example.com/testing_and_benchmarking 0.485s
以上就是基本的测试内容,如果你想深入学习 Go 语言的测试知识,如表驱动测试和子测试等,可以学习Prefer table driven tests,Go 官方文档 和 Go 博客 上的相关文章。