golang 单元测试
單元測試是質量保證十分重要的一環,好的單元測試不僅能及時地發現問題,更能夠方便地調試,提高生產效率。所以很多人認為寫單元測試是需要額外的時間,會降低生產效率,是對單元測試最大的偏見和誤解。
go 語言原生支持了單元測試,使用上非常簡單,測試代碼只需要放到以?_test.go?結尾的文件中即可。golang 的測試分為單元測試和性能測試,單元測試的測試用例以?Test?開頭,性能測試以?Benchmark?開頭。
舉個例子
實現排列組合函數對應的單元測試和性能測試。
實現排列組合函數
// combination.go package hmath func combination(m, n int) int {if n > m-n {n = m - n}c := 1for i := 0; i < n; i++ {c *= m - ic /= 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 intn intexpected 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) + 1n := 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
這個第三方工具會自動幫我們跑測試,并且以非常友好的可視化界面幫我們展示測試的結果,包括測試失敗的原因,測試覆蓋率等等,內部還提供了很多友好的斷言,能提高測試代碼的可讀性
使用方法
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 := 1Convey("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
?
轉載|出處:http://t.cn/RnvsFRp
Golang技術交流群:426582602
轉載于:https://www.cnblogs.com/reboot51/p/8669200.html
總結
以上是生活随笔為你收集整理的golang 单元测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 项目分层
- 下一篇: hihocoder1051 补提交卡(贪