eout
发布于

Go Test 单元测试简明教程 | 快速入门

原文 https://geektutu.com/post/quick-go-test.html

测试用例名称一般命名为 Test 加上待测试的方法名。

t *testing.T

测试用的参数有且只有一个,在这里是 t *testing.T。

testing.B

基准测试(benchmark)的参数是 *testing.B,TestMain 的参数是 *testing.M 类型。
b.ReportAllocs()
b.StopTimer()
b.StartTimer()

t.Helper()

用于标注该函数是帮助函数,报错时将输出帮助函数调用者的信息,而不是帮助函数的内部信息。

setup 和 teardown

如果在同一个测试文件中,每一个测试用例运行前后的逻辑是相同的,一般会写在 setup 和 teardown 函数中。例如执行前需要实例化待测试的对象,如果这个对象比较复杂,很适合将这一部分逻辑提取出来;执行后,可能会做一些资源回收类的工作,例如关闭网络连接,释放文件等。

TestMain(m *testing.M)

运行选中的测试方法时,走main主通道。
如果测试文件中包含该函数,那么生成的测试将调用 TestMain(m),而不是直接运行测试。TestMain 运行在主 goroutine 中 , 可以在调用 m.Run 前后做任何设置和拆卸。注意,在 TestMain 函数的最后,应该使用 m.Run 的返回值作为参数去调用 os.Exit。

func TestMain(m *testing.M) {
    r = NewRedisClient(&Config{Endpoint: "127.0.0.1:6379"}, prefix)
    fmt.Println("--1--")

    reset()
    c := m.Run()
    reset()
    fmt.Println("--2--")
    os.Exit(c)
}
func TestWriteShareCheckExst(t *testing.T) {
}

Examples are tests

Examples are compiled (and optionally executed) as part of a package’s test suite.

As with typical tests, examples are functions that reside in a package’s _test.go files. Unlike normal test functions, though, example functions take no arguments and begin with the word Example instead of Test.

浏览 (670)
点赞
收藏
评论