0
0

More than 3 years have passed since last update.

golang test coverage 100%を目指してみる

Posted at

golangでtestを書いてみたら、coverageが75%だったので、100%を目指してみる

そもそもどこが通ってないのか調べてみる

coverageをhtmlで可視化してくれるツールがあるので、それを流してみる。

go test  -coverprofile=cover.out
go tool cover -html=cover.out -o cover.html
open cover.html

これで、coverしているところは緑色に、してないところは赤になる。

関数ベースでみることもできる

$ go tool cover -func=cover.out
http2/http2.go:21: ServeHoge 100.0%
http2/http2.go:40: main 0.0%
total: (statements) 75.0%

mainが通ってなかったけど、どうするのこれ?

go でmainを並列処理にしてサーバを立てたあとに、Getを使って、サーバにアクセスすることでテストする。
deferでBodyをCloseするのを忘れないようにしろ、とのこと。

http2_test.go_part
func TestServer(t *testing.T) {
    go main()
    resp, err := http.Get("http://localhost:12344")
    if err != nil {
    t.Fatal(err)
    }   
    defer resp.Body.Close()
}                                                                                               

テストのカバレージの基準として、命令網羅(C0)、分岐網羅(C1)、条件網羅(C2)
という基準があるけど、このgoのtestは、C0でのカバレージを出しているとのこと。
たまにCIでカバレージ70%を基準にするという話を聞くけど、C1なのかなと思っていたけど、
どうなんだろ。今度見かけたら意識してみよう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0