测试main.go 中的Sum函数
sum_test.go
package demo
import (
"testing"
)
// 普通测试
func TestSum(t *testing.T) {
a := Sum(10,30)
if a == 40 {
log.Println(666)
}
}
go test 开始测试
多个测试数据使用案例
package demo
import (
"testing"
)
func TestSum(t *testing.T) {
// 存放测试数据的结构体
type test struct {
a int
b int
c int
}
//创建存放数据的测试用例map
dome := map[string]test{
"test1" : test{a:10, b:20, c:30},
"test2" : test{a:3, b:2, c:5},
"test3" : test{a:1, b:2, c:3},
}
for i, v := range dome {
t.Run(i, func(t *testing.T) {
result := Sum(v.a, v.b)
if result != v.c {
t.Errorf("测试用例:%v 失败,实际结果:%v, 用例结果:%v ",i,result,v.c)
}
})
}
}
开始测试
如果只想测试 test1 案例
go test -run /test1 -v
如果有多个测试案例
go test -run Sum/test1 -v (只测试Sum案例下的test1 数据)
代码测试覆盖率
go test -cover
go 还提供啦 -coverprofile 参数,将覆盖率记录到文件中
go test -cover -coverprofile=c.out (将记录存放在out文件中)
然后用html 方式查看 c.out文件
go tool cover -html=c.out
绿色就是覆盖率代码
package demo
import (
"testing"
)
//基准测试
func BenchmarkSum(b *testing.B) {
var n int
for i := 0; i < b.N; i++ {
n++
}
}
基准测试 需要添加 -bench 参数
因篇幅问题不能全部显示,请点此查看更多更全内容