单元测试 – 如何测量Golang中的代码覆盖率?

前端之家收集整理的这篇文章主要介绍了单元测试 – 如何测量Golang中的代码覆盖率?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有人成功地生成Go单元测试的代码覆盖?我在网上找不到一个工具。
注意 Go 1.2 (Q4 2013,rc1 is available)现在将显示 test coverage results

One major new feature of go test is that it can now compute and,with help from a new,separately installed “go tool cover” program,display test coverage results.

The cover tool is part of the 07002. It can be installed by running

$ go get golang.org/x/tools/cmd/cover

The cover tool does two things.

  • First,when “go test” is given the -cover flag,it is run automatically to rewrite the source for the package and insert instrumentation statements. The test is then compiled and run as usual,and basic coverage statistics are reported:
$ go test -coverprofile fmt
ok      fmt 0.060s  coverage: 91.4% of statements
$

Second,for more detailed reports,different flags to “go test” can create a coverage profile file,which the cover program,invoked with “go tool cover“,can then analyze.

Frank Shearar mentions

The latest versions of Go (2013/09/19) use:

go test -coverprofile <filename> <package name>

Details on how to generate and analyze coverage statistics can be found by running the commands

$ go help testflag
$ go tool cover -help

Ivan Black提及in the comments

go test -coverprofile cover.out and then
go tool cover -html=cover.out -o cover.html opens cover.html in browser

我甚至不想等待浏览器打开,所以我定义了这个别名:

alias gc=grep -v -e " 1$" coverage.out

我只是键入gc,并有一个列表,所有的线尚未覆盖(这里:coverage.out行不以“1”结束)。

原文链接:https://www.f2er.com/go/187773.html

猜你在找的Go相关文章