代码拉取完成,页面将自动刷新
https://geektutu.com/post/quick-go-test.html https://www.jianshu.com/p/1adc69468b6f
Go 语言推荐测试文件和源代码文件放在一块,测试文件以 _test.go
结尾。
example/
|--calc.go
|--calc_test.go
Test
加上待测试的方法名。t *testing.T
。*testing.B
,TestMain 的参数是 *testing.M
类型。package main
func Add(a int, b int) (int) {
return a + b
}
func minus(a int, b int) (int) {
return a - b
}
func mul(a int, b int) (int) {
return a * b
}
func div(a int, b int) (int) {
return a / b
}
package main
import "testing"
func TestAdd_1(t *testing.T) {
if ans := Add(1, 2); ans != 3 {
t.Errorf("1 + 2 expected be 3, but %d got", ans)
}
}
func TestAdd_2(t *testing.T) {
if ans := Add(-10, -20); ans != -30 {
t.Errorf("-10 + -20 expected be -30, but %d got", ans)
}
}
func TestAdd_3(t *testing.T) {
if ans := Add(-10, 10); ans != -0 {
t.Errorf("-10 + 10 expected be -0, but %d got", ans)
}
}
func Test_mul_1(t *testing.T) {
if ans := mul(1, 10) ; ans != 10 {
t.Errorf("1 * 10 expected be 10, but %d got", ans)
}
if ans := mul(1, -10) ; ans != -10 {
t.Errorf("1 * -10 expected be -10, but %d got", ans)
}
if ans := mul(0, -10) ; ans != -0 {
t.Errorf("0 * -10 expected be -0, but %d got", ans)
}
}
example$ go test -v
=== RUN TestAdd_1
--- PASS: TestAdd_1 (0.00s)
=== RUN TestAdd_2
--- PASS: TestAdd_2 (0.00s)
=== RUN TestAdd_3
--- PASS: TestAdd_3 (0.00s)
=== RUN Test_mul_1
--- PASS: Test_mul_1 (0.00s)
PASS
ok _/...../example 0.001s
$ go test -run TestAdd_3 -v
$go test
内置支持子测试
func TestMul(t *testing.T) {
t.Run("pos", func(t *testing.T) {
if mul(2, 3) != 6 {
t.Fatal("fail")
}
})
t.Run("neg", func(t *testing.T) {
if mul(2, -3) != -6 {
t.Fatal("fail")
}
})
}
// 推荐如下的写法
func TestMulComm(t *testing.T) {
cases := []struct {
Name string
A, B, Expected int
}{
{"pos", 2, 3, 6},
{"neg", 2, -3, -6},
{"zero", 2, 0, 0},
}
for _, c := range cases {
t.Run(c.Name, func(t *testing.T) {
if ans := mul(c.A, c.B); ans != c.Expected {
t.Fatalf("%d * %d expected %d, but %d got",
c.A, c.B, c.Expected, ans)
}
})
}
}
go test -v db_tenant_test.go db_test.go db_tenant.go logger.go
go test -v db_tenant_test.go db_test.go db_tenant.go logger.go -test.run TestSortPolicy
go test -v db_tenant_test.go db_test.go db_tenant.go logger.go -cover
# html文件输出
go test -v db_tenant_test.go db_test.go db_tenant.go logger.go -coverprofile cover.out
go tool cover -html=cover.out -o cover.html
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。