go testing:单元测试

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".
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值