Go單元測試

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.