链接
go test
运行TestXXX函数,go源码中的例子:https://github.com/golang/go/blob/go1.17/src/strings/strings_test.go
包名:xxx_test

go test -run name
go test -run name和go test -bench name的name参数是一个正则表达式,除非使用^...$,否则它们将执行部分匹配。
例子:
go test -run '' # 空参数,运行所有测试用例
go test -run Foo # 执行顶层测试函数,如"TestFooBar".
go test -run TestFoo # 执行顶层测试函数,如"TestFooBar", Test前缀可被自动跳过
go test -run Foo/A= # 执行顶层测试函数定义的的子测试逻辑,如"TestFooBar"中定义的名为"A"的子测试
go test -run /A=1 # 执行所有名为"A=1"的子测试
benchmark: go test -v -run NONE -bench BenchmarkFib10
// from fib_test.go
func BenchmarkFib10(b *testing.B) {
// run the Fib function b.N times
for n := 0; n < b.N; n++ {
Fib(10)
}
}
构建testbinary
go test -c -o path/to/testdir/testbin path/to/testdir/*.go &&\
path/to/testdir/testbin -v -run TestMethod
-c 编译
-o FILE 输出文件
-args [program args verbatim]
t.Skip("...")
测试用例可根据运行时参数动态跳过:
func TestTimeConsuming(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
...
}
读取testdata
参考:https://github.com/golang/go/blob/go1.17/src/archive/tar/reader_test.go#L688
测试用例执行时的工作目录是用例所在的目录,因此可以使用os.Open(....)直接读取相对路径的文件。

// file: go/src/archieve/tar/reader_test.go
func TestPartialRead(t *testing.T) {
f, err := os.Open("testdata/gnu.tar")
if err != nil {
t.Fatalf("Open() error: %v", err)
}
defer f.Close()
// do something on f
}
TestMain
如果存在TestMain函数,则go test忽略其他TestXXX和BenchXXX函数,直接运行TestMain.
func TestMain(m *testing.M) {
// call flag.Parse() here if TestMain uses flags
os.Exit(m.Run())
}
TestMain将会在主线程中执行,因此便于执行一些setup和teardown。
m.Run()执行所有的测试用例,然后返回exitCode。
注:一般情况下不需要使用TestMain。
example
在xx_test.go文件中的以ExampleXXX()开头的函数,例子:https://github.com/golang/go/blob/go1.17/src/strings/example_test.go

命名惯例:
func Example() { ... } // 针对包
func ExampleF() { ... } // 针对函数F
func ExampleT() { ... } // 针对类型T
func ExampleT_M() { ... } // 针对类型T的方法M
在运行测试用例时,方法体中有Output: 或者Unordered Output: 注释的方法,将会被执行,且输出会被与注释进行对比。
对比时,开头和结尾的空白字符将被忽略。
example文件命名一般为example_test.go,如果有其他额外的example,则加上一些前缀即可。

本文介绍了Go语言中的gotest工具,如何运行TestXXX函数,包括gotest-runname的正则表达式匹配,以及如何编写和执行测试案例、benchmark、TestMain和Example。还涵盖了工作目录、动态跳过测试、读取testdata等关键概念。
750

被折叠的 条评论
为什么被折叠?



