golang 單元測試

單元測試是質量保證十分重要的一環,好的單元測試不只能及時地發現問題,更可以方便地調試,提升生產效率,因此不少人認爲寫單元測試是須要額外的時間,會下降生產效率,是對單元測試最大的偏見和誤解git

go 語言原生支持了單元測試,使用上很是簡單,測試代碼只須要放到以 _test.go 結尾的文件中便可。golang的測試分爲單元測試和性能測試,單元測試的測試用例以 Test 開頭,性能測試以 Benchmark 開頭github

舉個例子

實現排列組合函數對應的單元測試和性能測試golang

實現排列組合函數

// 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)
            })
        })
    })
}

參考連接

轉載請註明出處
本文連接: http://hatlonely.github.io/20...
相關文章
相關標籤/搜索