测试工具 —go test
- go test命令用于对Go语言编写的程序进行测试。
测试规范
- 测试文件必须为"_test.go"为结尾, go test在执行时才会运行到相应的代码
- 测试代码必须 import testing 这个包
- 所有的测试用例函数必须是 Test 开头,测试函数
func TestXxxx(t *testing.T)
中,除了Xxxx可以不一样外,别的格式都不能改,参数是 testing.T ,我们可以使用该类型来记录错误或者是测试状态
- 函数中通过调用 testing.T 的 Error, Errorf, FailNow, Fatal, FatalIf 方法,说明测试不通过,调用 Log 方法用来记录测试的信息。
命令操作
go test -bench=.*
go test -v -test.run TestQueryYellowPagesMessageWithStaff
go test
测试方法—格驱动测试
package tests
import (
"math"
"testing"
)
//表格驱动设计
func TestTriangle(t *testing.T) {
tests := [] struct{a,b,c int}{
{1,2,3},
{3,4,5},
{0,0,0},
{4,5,6},
{100,200,20000},
}
for _, tt := range tests{
if actual := calcTriangle(tt.a,tt.b); actual != tt.c{
t.Error(" calcTriangle(tt.%d,tt.%d); got %d ;expected %d",
tt.a,tt.b,actual,tt.c)
}
}
}
func calcTriangle(a, b int) int {
var c int
c = int(math.Sqrt(float64(a*a + b*b)))
return c
}
网友评论