Go 語言基礎——go語言如何優雅的進行測試

咱們能夠爲Go程序編寫三類測試,即:功能測試(test)、基準測試(benchmark),也稱性能測試(example)shell

測試文件的約定

  1. 測試文件的主名稱應該以被測試文件主名稱爲先導,而且以_test爲後綴。例:demo.go 的測試文件名稱應爲demo_test.go。
  2. 通常狀況下一個測試文件只給一個源碼文件作測試,demo_test.go只測試demo.go文件。
  3. 測試文件與被測試文件應該放在同一個代碼包內

函數的名稱和簽名的規定

  1. 對於功能測試函數來講,其名稱必須以Test爲前綴,而且參數列表中只應有一個*testing.T類型的參數聲明。
  2. 對於性能測試函數來講,其名稱必須以Benchmark爲前綴,而且惟一參數的類型必須是*testing.B類型的。
  3. 對於示例測試函數來講,其名稱必須以Example爲前綴,對函數的參數列表沒有強制規定。
package demo

import (
	"fmt"
	"testing"
)
//功能測試
func TestMethod(t *testing.T)  {
	fmt.Println("function test")
}
//基準測試
func BenchmarkMethod(b *testing.B)  {
	fmt.Println("benchmark test")
}
//性能測試
func Examplemethod(t *testing.T)  {
	fmt.Println("example test")
}
func Method(t *testing.T)  {
	fmt.Println("Method")
}

go test 命令

go test 命令,會自動讀取源碼目錄下面名爲 *_test.go 的文件,生成並運行測試用的可執行文件。windows

運行go test 命令會運行符合規定的測試代碼;緩存

go test命令就會針對每一個被測代碼包,依次地進行構建、執行包中符合要求的測試函數,清理臨時文件,打印測試結果。函數

命令:性能

go test demo #go test [目錄]

這裏是否讀緩存不會影響咱們的測試結果,若是想清初緩存能夠執行: go clean -cache測試

性能測試
#格式:go test -bench=. -run=^$ [目錄]
go test -bench=. -run=^$ demo

-bench= 指要進行性能測試code

. 須要執行任意名稱的性能測試函數(符合規則)blog

-run=^$ 須要執行哪些功能的測試函數源碼

^$ 只執行名稱爲空的功能測試函數(不執行任何功能函數)io

輸出的內容:

function test benchmark test goos: windows goarch: amd64 pkg: demo BenchmarkMethod-8 benchmark test benchmark test benchmark test benchmark test benchmark test 2000000000 0.00 ns/op PASS ok demo 0.262s


**** 碼字不易若是對你有幫助請給個關注****

**** 愛技術愛生活 QQ羣: 894109590****

相關文章
相關標籤/搜索