網頁

2022/3/2

Golang 單元測試 顯示測試覆蓋率 unit test coverage rate

Go執行單元測試顯示測試覆蓋率(test coverage)的方式如下。


測試環境:

  • Go 1.17

例如專案目錄結構如下:

go-demo/
├── a/
│   ├── a_test.go
│   └── a.go
├── b/
│   ├── b_test.go
│   └── b.go
├── go.mod
└── main.go

專案module名稱為abc.com/demo


在專案根目錄執行go test -cover ./...可得到每個package的測試覆蓋率。

~/../go-demo$ go test -cover ./...
?       abc.com/demo    [no test files]
ok      abc.com/demo/a  (cached)        coverage: 100.0% of statements
ok      abc.com/demo/b  (cached)        coverage: 100.0% of statements

在專案根目錄執行go test "<package_name>" -cover可得到特定package的測試覆蓋率。<package_name>為要測試的package名稱。例如測試abc.com/demo/a package則執行go test "abc.com/demo/a" -cover

~/../go-demo$ go test "abc.com/demo/a" -cover
ok      abc.com/demo/a  (cached)        coverage: 100.0% of statements

在專案根目錄執行go test "<package_name>" -cover -run "^<test_func_name>$"可得到特定package的中特定測試函式的覆蓋率。<test_func_name>為測試函式名稱。例如執行abc.com/demo/apackage中的TestA_1測試則輸入go test "abc.com/demo/a" -cover -run "^TestA_1$"

~/../go-demo$ go test "abc.com/demo/a" -cover -run "^TestA_1$"
ok      abc.com/demo/a  (cached)        coverage: 75.0% of statements

若要取得全部package的測試覆蓋率,在專案根目錄執行go test --coverprofile=coverage.out ./...輸出所有package的測試結果到coverage.out,執行後可在根目錄看到多一個coverage.out

~/../go-demo$ go test --coverprofile=coverage.out ./...
?       abc.com/demo    [no test files]
ok      abc.com/demo/a  0.339s  coverage: 100.0% of statements
ok      abc.com/demo/b  0.583s  coverage: 100.0% of statements

然後執行go tool cover -func=coverage.out可看到總覆蓋率。

~/../go-demo$ go tool cover -func=coverage.out
abc.com/demo/a/a.go:5:  A               100.0%
abc.com/demo/b/b.go:5:  B               100.0%
total:                  (statements)    100.0%

或執行go tool cover -html=coverage.out可在瀏覽器顯示測試覆蓋的程式碼。綠色是有經過測試的程式碼,紅色為未經測試的程式碼。

~/../go-demo$ go tool cover -html=coverage.out



github


沒有留言:

張貼留言