Test & Benchmark
- 源码文件名需要以”_test.go”结尾
- 放置于需要测试模块的相同目录下
- 在build时会忽略所有test文件
Tests
定义
func TestXxx(*testing.T)
Benchmarks
定义
func BenchmarkXxx(*testing.B)
例子
func BenchmarkBigLen(b *testing.B) { big := NewBig() b.ResetTimer() //如果之前有耗费时间的启动设置,可以重置计算时间 for i := 0; i < b.N; i++ { big.Len() } }
func BenchmarkTemplateParallel(b *testing.B) { templ := template.Must(template.New("test").Parse("Hello, {{.}}!")) b.RunParallel(func(pb *testing.PB) { var buf bytes.Buffer for pb.Next() { buf.Reset() templ.Execute(&buf, "World") } }) }
Examples
定义
func ExampleXxx()
例子
//结束行需要有Output:开头的注释,用来比对标准输出(std.out)(忽略开头和结尾的空格) func ExampleSalutations() { fmt.Println("hello, and") fmt.Println("goodbye") // Output: // hello, and // goodbye }
命名规范
//suffix:在有多个example函数时,表示一个包/函数/类型/方法的名称 func Example_suffix() { ... } //package的example func ExampleF_suffix() { ... } //函数的example func ExampleT_suffix() { ... } //类型的example func ExampleT_M_suffix () { ... }//方法的example
当一个test文件没有包含test或benchmark函数时,包含至少一个example函数,则认为是一个example文件
Subtests & Sub-benchmarks
作用
- 增加了test的分层
- 可以共享setup(设置)和tear-down(销毁)过程
例子
//依次运行Subtests func TestFoo(t *testing.T){ //setup code t.Run("A=1",func(t *testing.T){...}) t.Run("A=2", func(t *testing.T) { ... }) t.Run("B=1", func(t *testing.T) { ... }) //tear-down code }
//并行运行Subtests func TestGroupedParallel(t *testing.T) { for _, tc := range tests { tc := tc // capture range variable t.Run(tc.Name, func(t *testing.T) { t.Parallel() //subtests彼此并行 ... }) } }
//Run在所有subtests完成前不会返回 func TestTeardownParallel(t *testing.T) { // This Run will not return until the parallel tests finish. t.Run("group", func(t *testing.T) { t.Run("Test1", parallelTest1) t.Run("Test2", parallelTest2) t.Run("Test3", parallelTest3) }) // }
Main
作用
- 开始测试时,首先运行TestMain
- 相当与测试的主线程
- 在TestMain中可以做一些Setup和Tear-down
- 最后应该使用os.Exit退出
例子
func TestMain(m *testing.M){ flag.Parse() os.Exit(m.Run()) }
go test命令
go test -run Foo # Run top-level tests matching "Foo". go test -run Foo/A= # Run subtests of Foo matching "A=". go test -run /A=1 # Run all subtests of a top-level test matching "A=1".