Go testing包用来为Golang提供单元测试、性能测试的功能。
介绍
若使用 testing 包,需要满足:
- 文件名使用
*_test.go
结尾
- 函数名以
TestXxx*(t *testing.T) 或 BenchmarkXxx(b *testing.B)
开头,测试未通过时,抛出 t.Error*
错误
触发命令:
go test
go test ./...
测试代码覆盖率
go test [./...|pkg] -coverprofile=cover.out
go tool cover -html cover.out
运行单个测试文件
go test -v utils/str_test.go utils/str.go
示例
$ mkdir hello
$ cat hello/calc.go
package hello
func Add(a, b int) int {
return a + b
}
$ cat hello/calc_test.go
package hello
import "testing"
func TestAdd(t *testing.T) {
s := Add(1, 2)
if s != 3 {
t.Errorf("run 1 + 2 == %d, not except 1 + 2 = 3", s)
}
}
执行测试
$ go test <module-name>/hello
ok <module-name>/hello 0.414s
显示测试覆盖率
$ go test leetcode/hello -coverprofile=cover.out
ok leetcode/hello 0.288s coverage: 100.0% of statements
$ cat cover.out
mode: set
leetcode/hello/calc.go:3.24,5.2 1 1
// 打开 html 报告
$ go tool cover -html cover.out
新能/基准测试
$ cat hello/calc_test.go
package hello
import "testing"
// 性能测试
func BenchmarkAdd(b *testing.B) {
for i := 1; i < 100; i++ {
Add(1, 2)
}
}
运行:
$ go test leetcode/hello -bench .
goos: darwin
goarch: amd64
pkg: leetcode/hello
cpu: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
BenchmarkAdd-12 1000000000 0.0000003 ns/op
PASS
ok leetcode/hello 0.592s
// 显示内存信息
$ go test leetcode/hello -bench . -benchmem
goos: darwin
goarch: amd64
pkg: leetcode/hello
cpu: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
BenchmarkAdd-12 1000000000 0.0000002 ns/op 0 B/op 0 allocs/op
PASS
ok leetcode/hello 3.193s
扩展