go test測試
阿新 • • 發佈:2020-12-15
go test測試
壓力測試用來檢測函式(方法)的效能,和編寫單元功能測試的方法類似。
壓力測試用例必須遵循如下格式,其中XXX可以是任意字母數字的組合,但是首字母不能是小寫字母
func BenchmarkXXX(b *testing.B) { ... }
go test不會預設執行壓力測試的函式,如果要執行壓力測試需要帶上引數-test.bench,語法:
-test.bench="test_name_regex",例如go test -test.bench=".*"表示測試全部的壓力測試函式
在壓力測試用例中,請記得在迴圈體內使用testing.B.N,以使測試可以正常的執行
檔名也必須以_test.go結尾
執行測試命令:
go test -file xx_test.go -test.bench=".*"
使用示例
package go_test_test import ( "errors" "testing" ) func Division(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("除數不能為0") } return a / b, nil } func Test_Division(t *testing.T) { if _, e := Division(6, 0); e == nil { //try a unit test on function t.Error("Division did not work as expected.") // 如果不是如預期的那麼就報錯 } else { t.Log("one test passed.", e) //記錄一些你期望記錄的資訊 } } func Benchmark_Division(b *testing.B) { for i := 0; i < b.N; i++ { //use b.N for looping Division(4, 5) } } func Benchmark_TimeConsumingFunction(b *testing.B) { b.StopTimer() //呼叫該函式停止壓力測試的時間計數 //做一些初始化的工作,例如讀取檔案資料,資料庫連線之類的, //這樣這些時間不影響我們測試函式本身的效能 b.StartTimer() //重新開始時間 for i := 0; i < b.N; i++ { Division(4, 5) } }