這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Go單元測試
簡介
單元測試是go語言層級提供的完整功能,測試代碼以*_test.go命名,單元測試的case以Test開頭,效能測試case以Benchmark開頭,運行測試命令:go test <test_file_list>
例子
實現排列組合函數以及對應的單元測試和效能測試
建立工程目錄結構
目錄結構說明參見規範-項目
└── src └── hmath ├── hmath.go └── hmath_test.go
實現排列組合函數
// src/hmath/hmath.gopackage hmathfunc combination(m, n int) int { if n > m-n { n = m - n } c := 1 for i := 0; i < n; i++ { c *= m - i c /= i + 1 } return c}
實現單元測試和效能測試
// src/hmath/hmath_test.gopackage hmathimport ( "math/rand" "testing")// 單元測試// 測試全域函數,以TestFunction命名// 測試類別成員函數,以TestClass_Function命名func TestCombination(t *testing.T) { // 這裡定義一個臨時的結構體來儲存測試case的參數以及期望的傳回值 for _, unit := range []struct { m int n int expected int }{ {1, 0, 1}, {4, 1, 4}, {4, 2, 6}, {4, 3, 4}, {4, 4, 1}, {10, 1, 10}, {10, 3, 120}, {10, 7, 120}, } { // 調用排列組合函數,與期望的結果比對,如果不一致輸出錯誤 if actually := combination(unit.m, unit.n); actually != unit.expected { t.Errorf("combination: [%v], actually: [%v]", unit, actually) } }}// 效能測試func BenchmarkCombination(b *testing.B) { // b.N會根據函數的已耗用時間取一個合適的值 for i := 0; i < b.N; i++ { combination(i+1, rand.Intn(i+1)) }}// 並發測試func BenchmarkCombinationParallel(b *testing.B) { // 測試一個對象或者函數在多線程的情境下面是否安全 b.RunParallel(func(pb *testing.PB) { for pb.Next() { m := rand.Intn(100) + 1 n := rand.Intn(m) combination(m, n) } })}
運行單元測試和效能測試
export GOPATH=$(pwd)go test src/hmath/*.go # 單元測試go test --cover src/hmath/*.go # 單元測試覆蓋率go test -bench=. src/hmath/*.go # 效能測試
上面命令的輸出如下:
hatlonely@localhost: ~/hatlonely/github/tmp $ go test src/hmath/hmath*.gook command-line-arguments 0.005shatlonely@localhost: ~/hatlonely/github/tmp $ go test --cover src/hmath/hmath*.gook command-line-arguments 0.005s coverage: 100.0% of statementshatlonely@localhost: ~/hatlonely/github/tmp $ go test -bench=. src/hmath/*.goBenchmarkCombination-8 100000 217618 ns/opBenchmarkCombinationParallel-8 3000000 401 ns/opPASSok command-line-arguments 23.599s