Go語言-測試用例

編寫單元測試用例

  • 文件名必須以'_test.go'結尾
  • 必須import "testing"這個包
  • 測試用例會按照源代碼中寫的順序依次執行
  • 測試函數'TestXxx(t *testing.T)'中的參數是‘testing.T’,我們可以用該類型來記錄錯誤或者是測試狀態
  • 測試格式:‘func TestXxx(t *testing.T)’,'Xxx'部分可以爲任意的字母數字組合,但是首字母不能是小寫字母[a-z]
  • 函數中通過調用'testing.T'的'Error'、'Errorf'、'FailNow'、'Fatal'、‘FatalIf’方法,說明測試用例不通過,調用''Log'方法用來記錄測試的信息

編寫壓力測試

  • 壓力測試用例必須遵循如下格式,其中XXX可以是任意字母數字的組合,但是首字母不能是小寫字母
    func BenchmarkXXX(b *testing.a) {...}
  • go test 不會默認執行壓力測試的函數,如果要執行壓力測試需要帶上參數。-test.bench,語法: -test.bench="test_name_regex" ,例如 go test -test.bench=".*"表示測試全部的壓力測試函數
  • 在壓力測試用例中,需要才循環體內使用testing.B.N,以使測試用例正常運行
  • 文件名也必須以_test.go結尾

單元測試用例

源碼

    package gotest

    import(
    )

    func Add(a, b float64) float64 {
        return a +  b
    }

測試用例

package gotest

import (
    "testing"
)

func Test_Add_1(t *testing.T) {
    if i := Add(6,2); i != 8 {
        t.Error("fail")
    } else {
        t.Log("pass")
    }
}

func Test_Add_2(t *testing.T) {
    if i := Add(6,2); i == 8 {
        t.Log("pass")
    } else {
        t.Error("fail")
    }
}

運行測試用例

    go test -v

測試用例執行結果

=== RUN   Test_Add_1
--- PASS: Test_Add_1 (0.00s)
    gotest_test.go:11: pass
=== RUN   Test_Add_2
--- PASS: Test_Add_2 (0.00s)
    gotest_test.go:17: pass
PASS
ok      github.com/shadowsocks/shadowsocks-go/sample-config/gotest  0.001s

壓力測試用例

源碼

package gotest

import(
    "testing"
)

func Benchmark_Add(b *testing.B) {
    for i := 0; i < b.N ; i++ {
        Add(3,4)
    }
}

func Benchmark_TimeConsumingFunction(b *testing.B) {
    b.StopTimer() //調用該函數停止壓力測試的時間計數
    //做一些初始化工作,這些時間不影響我們測試函數本身的性能
    b.StartTimer()

    for i := 0; i < b.N; i++ {
        Add(5,6)
    }
}

運行結果

Benchmark_Add-4                         2000000000           0.38 ns/op
Benchmark_TimeConsumingFunction-4       2000000000           0.38 ns/op
PASS
ok      github.com/shadowsocks/shadowsocks-go/sample-config/gotest  1.594s

第一條顯示Benchmark_add-4執行了20億次,每次執行時間爲0.38納秒
第二條也一樣
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章