單元測試是質量保證十分重要的一環,好的單元測試不僅能及時地發現問題,更能夠方便地調試,提高生產效率,所以很多人認爲寫單元測試是需要額外的時間,會降低生產效率,是對單元測試最大的偏見和誤解
go 語言原生支持了單元測試,使用上非常簡單,測試代碼只需要放到以 _test.go 結尾的文件中即可。golang的測試分爲單元測試和性能測試,單元測試的測試用例以 Test 開頭,性能測試以 Benchmark 開頭
舉個例子
實現排列組合函數對應的單元測試和性能測試
實現排列組合函數
// combination.go
package hmath
func 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
}
實現單元測試和性能測試
// combination_test.go
package hmath
import (
"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)
}
})
}
運行測試
go test combination_test.go combination.go # 單元測試
go test --cover combination_test.go combination.go # 單元測試覆蓋率
go test -bench=. combination_test.go combination.go # 性能測試
setup 和 teardown
setup 和 teardown 是在每個 case 執行前後都需要執行的操作,golang 沒有直接的實現,可以通過下面這個方法實現全局的 setup 和 teardown,具體每個 case 的 setup 和 teardown 需要自己實現
func TestMain(m *testing.M) {
// setup code...
os.Exit(m.Run())
// teardown code...
}
goconvey
這個第三方工具會自動幫我們跑測試,並且以非常友好的可視化界面幫我們展示測試的結果,包括測試失敗的原因,測試覆蓋率等等,內部還提供了很多友好的斷言,能提高測試代碼的可讀性
使用方法
go get github.com/smartystreets/goconvey
然後用終端在測試代碼的目錄下運行 goconvey 命令即可
測試例子
package package_name
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestIntegerStuff(t *testing.T) {
Convey("Given some integer with a starting value", t, func() {
x := 1
Convey("When the integer is incremented", func() {
x++
Convey("The value should be greater by one", func() {
So(x, ShouldEqual, 2)
})
})
})
}
參考鏈接
- go testing: http://docs.studygolang.com/pkg/testing/
- goconvey: https://github.com/smartystreets/goconvey
- goconvey 文檔: https://github.com/smartystreets/goconvey/wiki/Documentation
- [goconvey 標準斷言: https://github.com/smartystreets/goconvey/wiki/Assertions
- thumb_up](https://github.com/smartystreets/goconvey/wiki/Assertions)
轉載請註明出處
原文文鏈接:http://hatlonely.github.io/2018/01/31/golang-單元測試/
【51Reboot】Golang 課程3月24日開班,詳情諮詢 WeChat : 1902433859 小月