概要
よく忘れるので、ここにメモメモ。。。
goでカバレッジを採取した後、それをHTMLで出力するには以下のようにします。
$ go test -coverprofile /path/to/coverage/result ./... $ go tool cover -html /path/to/coverage/result -o /path/to/html/result
サンプル
Taskfile.yml
version: "3" tasks: default: cmds: - task: clean - task: run - task: preview clean: cmds: - rm -f {c.out,c.out.html} run: cmds: - go test -coverprofile c.out . - go tool cover -html c.out -o c.out.html preview: cmds: - python3 -m http.server 8888
lib.go
コードに意味は無いです。
package main func Plus[T ~int](x, y T) T { if x == 100 { return y } return x + y }
lib_test.go
package main import "testing" func TestPlus(t *testing.T) { // Arrange var ( x = 1 y = 2 expected = 3 ) // Act result := Plus(x, y) // Assert if result != expected { t.Errorf("[want] %v\t[got] %v", expected, result) } }
実行結果
gitpod /workspace/try-golang (master) $ task -d examples/singleapp/coverage_html_out/ task: [clean] rm -f {c.out,c.out.html} task: [run] go test -coverprofile c.out . ok github.com/devlights/try-golang/examples/singleapp/coverage_html_out 0.002s coverage: 66.7% of statements task: [run] go tool cover -html c.out -o c.out.html task: [preview] python3 -m http.server 8888 Serving HTTP on 0.0.0.0 port 8888 (http://0.0.0.0:8888/) ...
簡易でhttpサーバを起動しています。んで、出力したHTMLファイルにアクセスすると以下のような感じ。
参考情報
過去の記事については、以下のページからご参照下さい。
サンプルコードは、以下の場所で公開しています。