1. 简介
Go 语言中自带有一个轻量级的测试框架 testing 和自带的 go test 命令来实现单元测试和性能测试。
2. 要求
3. 案例
gotest.go
package gotest
import ( "errors")
func Division(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("除数不能为0")
} return a / b, nil
}
View Code
gotest_test.go
package gotest
import ( "testing")
func Test_Division_1(t *testing.T) { if i, e := Division(6, 2); i != 3 || e != nil {
t.Error("除法函数测试没通过")
} else {
t.Log("第一个测试通过")
}
}
func Test_Division_2(t *testing.T) {
t.Error("就是不通过")
}
View Code
4. 压力测试
5. 案例
webbench_test.go
package gotest
import ( "testing")
func Benchmark_Division(b *testing.B) { for i := 0; i < b.N; i++ {
Division(4, 5)
}
}
func Benchmark_TimeConsumingFunction(b *testing.B) {
b.StopTimer()
b.StartTimer() for i := 0; i < b.N; i++ {
Division(4, 5)
}
}
View Code
命令行执行: go.exe test -test.bench=.*