[Note] Golang Test 測試筆記
- Testing in Go @ ieftimov
- 如何在 Go 專案內寫測試 @ AppleBoy
CLI
# -v 顯示詳細測試結果(verbose)
# -cover 顯示測試覆蓋率
# -failfast 發生錯誤就停止測試
# -coverprofile 產生測試結果的檔案
# -html 產生測試結果的 HTML 檔案
# -short 跳過有 t.Skip 或 testing.Short() 的函式
# 測試某個 package
$ go test <package-name> -v
$ go test sandbox/go-sandbox/car -v
# 測試專案內的所有檔案
$ go test ./...
# 測試某資料夾內的所有檔案
$ go test ./car/...
# 只測試檔案中的某個 function
$ go test -run=TestCar_SetName -cover -v ./car/...
# 檢視測試覆蓋率
$ go test -cover . # 只顯示在 Terminal
# 檢視測試報告及未被覆蓋到的程式碼
$ go test -coverprofile cover.out ./...
$ go tool cover -html=cover.out -o cover.html
$ open cover.html
# 清除測試的 cache
$ go clean -testcache
# 避免多個 package 的 test 同時執行
$ go test -p 1 ./... # 限制 parallel 的數量為 1
建立測試
建立測試檔
依照慣例,假設我們要測試的是 main.go
- 測試檔會直接放在要被測試的檔案旁邊
- 檔名「必須」為
main_test.go