整理自https://liumiaocn.blog.csdn.net/article/details/54922394
自动化测试
go程序测试
例子
自动化测试
basicfunc.go
package basicfunc
func GetGrade(score int) string {
switch {
case score < 60:
return "D"
case score <= 70:
return "C"
case score <= 80:
return "B"
case score <= 90:
return "A"
default:
return "Undefined"
}
}
func Add(num1 int, num2 int) int {
return num1 + num2
}
func_test.go
package basicfunc
import "testing"
// 功能测试:testing.T
func TestBasic(test *testing.T) {
grade := GetGrade(40)
if grade != "D" {
test.Error("Test Case failed.")
}
}
func TestAddfunc(test *testing.T) {
sum := Add(1, 1)
if sum == 2 {
test.Log("Passed: 1 + 1 == 2 ")
} else {
test.Log("Failed: 1 + 1 == 2 ")
}
}
// 压力测试:testing.B
func BenchmarkAddfunc(bmtest *testing.B) {
for cnt := 0; cnt < bmtest.N; cnt++ {
Add(1, 1)
}
}
如何执行
1.执行go mod init
2. 功能测试:go test
3. 压力测试:go test -bench=.
常用参数
-bench regexp 执行相应的 benchmarks,例如 -bench=.;
-cover 开启测试覆盖率;
-run regexp 只运行 regexp 匹配的函数,例如 -run=Array 那么就执行包含有 Array 开头的函数;
-v 显示测试的详细命令。
执行结果
覆盖率
概念
测试覆盖率是通过执行某包的测试用例来确认代码被执行的程度的术语。
统计模式
执行
go test -cover
得到覆盖率
可以看到我们现在得到了一个42.9%的覆盖率,这说明42.9%的代码在测试用例执行中被至少执行过一次。
生成HTML
生成前的准备
go test -coverprofile=covprofile
生成covprofile 文件
生成HTML文件
go tool cover -html=covprofile -o coverage.html
生成HTML文件