首页 > 应用开发 > IT综合 > Go语言单元和性能测试的相关文档
单元测试很重要,Go语言提供了相关的单元测试框架。允许对单个和一系列文件进行自动化测试。
Package testing provides support for automated testing of Go packages. It is intended to be used in concert with the “go test” command, which automates execution of any function of the form
测试用例写法
函数名称必须以Test开头,例如
func TestXxx(*testing.T)where Xxx can be any alphanumeric string (but the first letter must not be in [a-z]) and serves to identify the test routine. These TestXxx routines should be declared within the package they are testing.
go文件命名
必须是_test.go为后缀(*_test.go)。此外,package名最好不要用main.
举例, funcs_test.go
package mytest
import "testing"
func TestSomething(t *testing.T) {
//call some function
}
func TestAnotherthing(t *testing.T) {
//call some function
}
go test
将对当前目录下的所有*_test.go文件进行编译并自动运行测试。
使用”-file”参数。go test –file **.go 。例如,
go test -file b_test.go
”-file”参数不是必须的,可以省略。如果你输入go test b_test.go也会得到一样的效果
warning: GOPATH set to GOROOT (c:go) has no effect
PASS
ok _/F_/workspace/goSample01/src/test 0.359s
go test -run=’ TestSomething’
性能测试对于对比和改进算法很有帮助。因此,Go语言提供了相关的函数性能测试框架。当然,Go只是提供了基本测试框架,真正的测试代码还得由程序员来完成。
Benchmark测试用例写法:
函数命名必须以Benchmark打头。例如,
func BenchmarkXxx(*testing.B)are considered benchmarks, and are executed by the "go test" command when the -test.bench flag is provided.
A sample benchmark function looks like this:
func BenchmarkHello(b *testing.B) { for i := 0; i < b.N; i++ { fmt.Sprintf("hello") }} 在命令行里输入:go test . -bench="."
(注意:同一个包里面不能有相同的方法名。否则,可能会编译出错)
F:workspacegoSample01srctest>go test . -bench="."
warning: GOPATH set to GOROOT (c:go) has no effect
PASS
BenchmarkUpdate 500000 4906 ns/op
BenchmarkManual 200000 8750 ns/op
BenchmarkUnroll 500000 4531 ns/op
BenchmarkLoop 2000000000 0.00 ns/op
BenchmarkIteratively 1000000 2078 ns/op
在命令行里输入:go test b_test.go -bench="."
F:workspacegoSample01srctest>go test b_test.go -bench="."
warning: GOPATH set to GOROOT (c:go) has no effect
PASS
BenchmarkUpdate 500000 4562 ns/op
BenchmarkManual 200000 9062 ns/op
BenchmarkUnroll 500000 4187 ns/op
ok command-line-arguments 6.953s
1、循环次数和每次操作的时间
The benchmark package will vary b.N until the benchmark function lasts long enough to be timed reliably. The output
testing.BenchmarkHello 10000000 282 ns/opmeans that the loop ran 10000000 times at a speed of 282 ns per loop.
2、计时器可以手工控制
If a benchmark needs some expensive setup before running, the timer may be stopped:
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/88031/viewspace-1058532/
,如需转载,请注明出处,否则将追究法律责任。