5.go开源groupcache项目笔记——关于testing

来源:互联网 发布:c语言while是什么意思 编辑:程序博客网 时间:2024/05/18 00:56

5.go开源groupcache项目笔记——关于testing

Go语言通过testing包提供自动化测试功能。包内测试只要运行命令 go test,就能自动运行符合规则的测试函数。

Go语言测试约定规则

1.一般测试funcTestXxx(*testing.T)测试行必须Test开头,Xxx为字符串,第一个X必须大写的[A-Z]的字幕。为了测试方法和被测试方法的可读性,一般Xxx为被测试方法的函数名。

2.性能测试funcBenchmarkXxx(*testing.B),性能测试用Benchmark标记,Xxx同上。

3.测试文件名约定,go语言测试文件名约定规则是必须以_test.go结尾,放在相同包下,为了方便代码阅读,一般go源码文件加上_test。比如源文件my.go 那么测试文件如果交your_test.go,her_test.go,my_test.go都可以,不过最好的还是my_test.go,方便阅读

1      示例

1.1     创建 my.go文件

packagemy

funcadd(x,yint)int{

    returnx+y

}

1.2     创建my_test.go

packagemy
 
import"testing"
 
funcTestAdd(t*testing.T){
    ifadd(1,2)!=3{
        t.Error("testfoo:Addrfailed")
    }else{
        t.Log("testfoo:Addrpass")
    }
}
 
funcBenchmarkAdd(b*testing.B){
    //如果需要初始化,比较耗时的操作可以这样:
    //b.StopTimer()
    //....一堆操作
    //b.StartTimer()
    fori:=0;i<b.N;i++{
        add(1,2)
    }
}

1.3     执行输出

运行测试 go test,输出:

=== RUN TestAdd

--- PASS: TestAdd (0.00s)

my_test.go:9: test foo:Addr pass

PASS

ok test0.266s

更多测试命名,用gohelp test

阅读全文
0 0
原创粉丝点击