??Golang中內置了對單元測驗的支持,不需要像Java一樣引入第三方Jar才能進行測驗,下面將分別介紹Golang所支持的幾種測驗;
一、測驗型別
??Golang中單元測驗有功能測驗、基準測驗、示例測驗或稱示例函式三種;
??功能測驗必須以TestXXX函式名出現,基準測驗必須以BenchmarkXXX函式名出現,示例函式必須以ExampleXXX函式名出現,
//功能測驗
func TestXXX(t *testing.T){
}
//基準測驗
func BenchmarkXXX(b * testing.B){
}
//示例函式
func ExampleXXX(){
}
二、功能測驗
??函式名:TestXxx,以Test為前綴的功能測驗函式
??引數型別:*testing.T
??功能函式:
func(a, b int) Mul {
return b * b
}
測驗函式:
func TestMul(t *testing.T) {
arr := [...]int{2, 4, 6}
expected := []int{8, 12}
for j := 0; j < 2; j++ {
result := Add(arr[j], arr[j+1])
if result != expected[j] {
//失敗后停止后序邏輯
t.Fatalf("input is %d, the expected is %d, the actual %d", arr[j], expected[j], result)
//失敗后繼續執行后序邏輯
//t.Errorf("input is %d, the expected is %d, the actual %d", arr[j], expected[j], result)
}
}
}
二、基準測驗
??用于對程式功能進行可定量、可對比的性能測驗;
??函式名:BenchmarkXxx,以Test為前綴的測驗功能函式
??引數型別:*testing.B
func BenchmarkMul(b *testing.B) {
for i := 0; i < b.N; i++ {
Mul(i, i)
}
}
執行結果:
goos: windows
goarch: amd64
pkg: solinx.co/LCache/test
BenchmarkMul-12 1000000000 0.323 ns/op
PASS
coverage: 100.0% of statements
ok solinx.co/LCache/test 0.499s
結果分析:
執行執行環境:windows
架構:amd64
包路徑
BenchmarkMul-12:總共12個邏輯cpu
函式執行時間 0.499秒
測驗代碼覆寫率:100%
三、示例測驗
func ExampleMul() {
a := Mul(2, 2)
fmt.Println(a)
//Output: 41
}
??輸出內容到標準輸出,引數沒有限制;go test執行時會監測實際輸出與注釋中的期望結果是否一致,一致時測驗通過,不一致則測驗失敗;
通過:

失敗:
=== RUN ExampleMul
--- FAIL: ExampleMul (0.00s)
got:
4
want:
41
FAIL
coverage: 100.0% of statements
得到了:4,需要的是:41 測驗失敗;
四、go test 引數介紹
??-count: 設定執行測驗函式的次數, 默認 1
??-run: 執行功能測驗函式, 可正則匹配
??-bench: 執行基準測驗函式, 可正則匹配
??-benchtime: 基準測驗最大探索時間
??-parallel: 設定功能測驗函式最大并發執行數
??-v: 是展示測驗程序資訊
??-cover:顯示測驗代碼覆寫率
??-list : 列出所匹配的測驗函式,不執行
執行與Test匹配的測驗函式
go test -run Test
文章首發地址:Solinx
https://mp.weixin.qq.com/s/nqnXiOT_CfD6qWeE6xsrhw
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/38553.html
標籤:Go
上一篇:Golang中的Slice與陣列
下一篇:go實作java虛擬機01
