1、测试用例的go文件,和被测试的go文件在同一个包下,以_test.go结尾
2.单元测试函数以Test开头,t *testing.T为参数,无返回值
// calc.go 文件package calc
func Add(a ,b int) int {return a + b}
func Sub(a, b int) int {return a - b}
package calc_test// calc_test.go文件import ("github.com/business_group/test_project/calc""testing")
func TestAdd(t *testing.T) {ret := calc.Add(1, 2)want := 3if ret != want {t.Fatalf("want:%v, but got:%v ", want, ret)}}
func TestAdd1(t *testing.T) {ret := calc.Add(-1, -2)want := -3if ret != want {t.Fatalf("want:%v, but got:%v ", want, ret)}}
func TestSub(t *testing.T) {ret := calc.Sub(1, 3)want := -2if ret != want {t.Fatalf("want:%v, but got:%v ", want, ret)}}
func TestSub1(t *testing.T) {ret := calc.Sub(-1, 3)want := -4if ret != want {t.Fatalf("want:%v, but got:%v ", want, ret)}}
3、执行单元测试使用命令`go test` 或者 `go test -v`
测试组testGroup:
将多个测试用例放在一个函数内, 测试数据放在切片里,循环切片
package calc_test
// calc_test.go文件import ("github.com/business_group/test_project/calc""testing")
func TestAdd(t *testing.T) {type testCase struct {a intb intwant int}testGroup := []*testCase{&testCase{1, 2, 3},&testCase{0, 2, 2},&testCase{-1, -2, -3},}
for _, tc := range testGroup {got := calc.Add(tc.a, tc.b)if got != tc.want {t.Fatalf("want:%v, but got:%v ", tc.want, got)}}}
执行测试组: `go test` 或 `go test -v`
子测试
给切片中的测试用例起名字,把测试用例放在map中
package calc_test
// calc_test.go文件import ("github.com/business_group/test_project/calc""testing")
func TestAdd(t *testing.T) {type testCase struct {a intb intwant int}testGroup := map[string]*testCase{"case_1": &testCase{1, 2, 3},"case_2": &testCase{0, 2, 2},"case_3": &testCase{-1, -2, -3},}
for name, tc := range testGroup {t.Run(name, func(t *testing.T) {got := calc.Add(tc.a, tc.b)if got != tc.want {t.Fatalf("want:%v, but got:%v ", tc.want, got)}})}}
执行 `go test ` 或者 `go test -v`
单独跑TestAdd函数的case_1用例: `go test -run=TestAdd/case_1`
测试覆盖率
看我的测试用例覆盖了多少行代码。(测试用例不可能每个分支都考虑到)
查看测试覆盖率,命令:`go test -cover`
将测试覆盖详细信息输出到c.out文件: `go test -cover -coverprofile=c.out`
用html工具查看c.out文件(可以用别的查看):`go tool cover -html=c.out` 绿色为覆盖到了,红色为没覆盖到
测试函数覆盖率:100%覆盖
测试代码覆盖率:60%以上