Go本身提供了一套轻量级的测试框架。
demo.go
package demo func Add(a, b int) int { return a + b }demo_test.go
package demo import "testing" func TestAdd(t *testing.T) { // 测试成功 t.Log(Add(1, 2)) // 测试失败 //t.Fatal("demo") }执行结果:
yimt@MacBook-Pro demo % go test . ok demo 0.497sdemo.go
package demo func Add(a, b int) int { return a + b }demo_test.go
package demo import ( "testing" ) func BenchmarkAdd(b *testing.B) { // 开始计时 b.StartTimer() b.Log(Add(1, 2)) // 结束计时 b.StopTimer() }执行结果:
yimt@MacBook-Pro demo % go test -test.bench=".*" goos: darwin goarch: amd64 pkg: demo BenchmarkAdd-12 1000000000 0.000015 ns/op --- BENCH: BenchmarkAdd-12 demo_test.go:10: 3 demo_test.go:10: 3 demo_test.go:10: 3 demo_test.go:10: 3 demo_test.go:10: 3 demo_test.go:10: 3 PASS ok demo 0.217s