1 Star 0 Fork 0

田圃森 / learn-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.gotest.md 3.01 KB
一键复制 编辑 原始数据 按行查看 历史
普森 提交于 2022-09-25 12:18 . basic 01-05

go test

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
  • 基准测试(benchmark)的参数是 *testing.B,TestMain 的参数是 *testing.M 类型。

calc.go

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
}

calc_test.go

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

子测试(Subtests)

内置支持子测试

常规写法

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
Go
1
https://gitee.com/pustian/learn-go.git
git@gitee.com:pustian/learn-go.git
pustian
learn-go
learn-go
master

搜索帮助