⭐在go里面使用自带的test

go test 是 Go 语言内置的测试工具,用于执行测试程序并生成测试报告

执行当前目录的所有测试

go test

执行制定包下的所有测试

go test path/src/package

不包括带有tags的测试文件

执行指定函数

go test -run TestFuncName

不包括带有tags的测试文件,testFuncName是执行的函数名称

指定测试文件

go test path/src/package/foo_test.go

指定测试超时时间

go test -timeout 5s

5s是超时时间,可是任意有效的时间格式字符串

输出覆盖率报告

go test -cover

覆盖率报告写入到文件

go test -cover -coverprofile=cover.out

查看测试允许的函数

go test -v

执行指定标签测试

定义一个带有tags的测试文件

// +build foo

package mytest

import "testing"

func TestState(t *testing.T) {
	err := nil
	if err != nil {
		t.Error(err)
	}
}

指定单个tags运行测试 go test –tags=foo

定义多个tags:

// +build foo || bar

运行go test –tags=foo 或者 go test –tags=bar都能调用测试文件

排除tags执行:

// +build !foo

运行传入tags不等于foo都会被调用

执行测试

go test --tags=foo

–tags多个使用,分割如–tags=foo,bar

testing.T

1.t.Log:在测试中记录信息,不影响测试结果

func testFunc(t *testing.T){
    t.Log("Starting test...")   
}

2.t.Errorf:在测试中记录错误信息,并标记测试失败

func testFunc(t *testing.T){
    t.Errorf("Vaild fail(%s)", "username")
}

3.t.FailNow:标记测试失败,并立即终止测试

func testFunc(t *testing.T){
    err := errors.New("Is a error")
    if err != nil{
        t.FailNow()
    }
}

4.t.Skip:标记测试跳过

func testFunc(t *testing.T){
    err := errors.New("Is a error")
    if err == nil{
        t.Skip("Skipping test")
    }
}

5.t.Run:在测试函数中嵌套子测试

func testFunc(t *testing.T){
    t.Run("Case 1", func(t *testing.T) {
        // 测试代码
    })
    t.Run("Case 2", func(t *testing.T) {
        // 测试代码
    })
}

6.t.Helper:标记函数是测试的辅助函数,使得测试失败时能够快速定位错误发生位置

func testFunc(t *testing.T){
    t.Helper()
}

7.t.Logf: 在测试中记录信息,可以格式化结构,不影响测试结果

func testFunc(t *testing.T){
    t.Logf("Runtime %s", "once")
}

8.TempDir: 获取测试使用的临时目录

func (c *common) TempDir() string

9.Setenv: 设置测试中的环境变量

func (t *T) Setenv(key, value string)

10.CleanUp: 测试完成时调用,会清除通过Setenv设置的环境变量

func (c *common) Cleanup(f func())