介绍
编写单元测试规范
1、文件名:_test.go 结尾
2、函数名:Test 开头
3、入参:(t *testing.T)
4、内置库:testing
5、报错信息:使用 testing 内置的方法:Errorf、Error 、Fail、Failed、Fatal、Fatalf、Log、Logf 等
执行单元命令
执行命令
:go test
接下来我们举例说明,光说不写等于耍流氓。
- 单元测试
先写个函数如下:
package study
func CalNumber(a int, b int) int {
c := a + b
return c
}
接下来编写测试用例:
package study
import (
"testing"
)
func TestCalNumber(t *testing.T) {
result := CalNumber(1, 3)
if result != 3 {
t.Errorf("wrong: result=%d actual=%d", result, 3)
}
}
然后执行命令:
BDSHYF000116923:study $ go test math_test.go math.go
--- FAIL: TestCalNumber (0.00s)
math_test.go:11: wrong: result=4 actual=3
FAIL
FAIL command-line-arguments 0.005s
是不是很简单?你有没有学会,实际go test提供很多功能,还包括覆盖率测试,性能测试等等。
- 覆盖率测试
BDSHYF000116923:study $ go test --cover math_test.go math.go
ok command-line-arguments 0.005s coverage: 100.0% of statements
性能测试
示例代码如下:
package study
import (
"math/rand"
"testing"
)
//单元测试
func TestCalNumber(t *testing.T) {
result := CalNumber(1, 2)
if result != 3 {
t.Errorf("wrong: result=%d actual=%d", result, 3)
}
}
// 性能测试
func BenchmarkCalNumber(b *testing.B) {
// b.N会根据函数的运行时间取一个合适的值
for i := 0; i < b.N; i++ {
CalNumber(i+1, rand.Intn(i+1))
}
}
执行命令如下:
BDSHYF000116923:study $ go test -bench=. math_test.go math.go
goos: darwin
goarch: amd64
BenchmarkCalNumber-4 50000000 30.3 ns/op
PASS
ok command-line-arguments 1.553s
总结
实际golang内置的 testing 库其实挺好用的,但遇到复杂的问题,还是需要即用一些成熟的第三方库的测试框架。比如:
GoConvey是一款针对Golang的测试框架,可以管理和运行测试用例,同时提供了丰富的断言函数,并支持很多 Web 界面特性。
代码地址:https://github.com/zf766045962/go-study/tree/master/study
下一节:介绍goconvey