go test用于编译单元测试,检测方法函数是否有问题,熟悉下相关参数,可以让测试过程更新快捷
go test
go test math.go math_test.go
go test -v
go test -v -run="TestAddMore"
go test -c
go test -v -o math.test.exe
go test -v -cover math.go math_test.go
创建一个math.go
,写一个add的Func函数,如下
package main
func Add(x, y int) int {
return x + y
}
同级建立一个math_test.go
的测试文件
package Test
import "testing"
type TestTable struct {
xArg int
yArg int
}
// 简单测试,单元测试
func TestAdd(t *testing.T) {
t.Log(Add(1, 2))
}
// 少量样例测试,表组测试
func TestAddMore(t *testing.T) {
sum := Add(1, 2)
if sum == 3 {
t.Log("the result is ok")
} else {
t.Fatal("the result is wrong")
}
sum = Add(2, 4)
if sum == 6 {
t.Log("the result is ok")
} else {
t.Fatal("the result is wrong")
}
}
// 大量测试样例,表格测试法
func TestAddMoreAndMore(t *testing.T) {
tables := []TestTable{
{1, 2},
{2, 4},
{4, 8},
{5, 10},
{6, 12},
}
for _, table := range tables {
result := Add(table.xArg, table.yArg)
if result == (table.xArg + table.yArg) {
t.Log("the result is ok")
} else {
t.Fatal("the result is wrong")
}
}
}
// === RUN TestAdd
// math_test.go:12: 3
// --- PASS: TestAdd (0.00s)
// === RUN TestAddMore
// math_test.go:19: the result is ok
// math_test.go:26: the result is ok
// --- PASS: TestAddMore (0.00s)
// === RUN TestAddMoreAndMore
// math_test.go:45: the result is ok
// math_test.go:45: the result is ok
// math_test.go:45: the result is ok
// math_test.go:45: the result is ok
// math_test.go:45: the result is ok
// --- PASS: TestAddMoreAndMore (0.00s)
// PASS
_test.go
结尾,最好就是 被测试文件_test.go
,Test
开口,如TestAdd
testing.T
类型的指针,而且不返回任何值参考,未尝试
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。