如何在Go中衡量测试覆盖率 [英] How to measure test coverage in Go
问题描述
有人成功地为Go单元测试生成了代码覆盖率吗?我在网络上找不到用于该工具的工具.
Has anyone succeeded in generating code coverage for Go unit tests? I can't find a tool for that on the web.
推荐答案
请注意,测试覆盖率结果 :
Note that Go 1.2 (Q4 2013, rc1 is available) will now display test coverage results:
go test
的一项主要新功能是,它现在可以计算并在新的,单独安装的"go工具保护套
"程序的帮助下,显示测试覆盖率结果.
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.
cover
工具是 go.tools
子存储库.可以通过运行来安装
The cover
tool is part of the go.tools
subrepository. It can be installed by running
$ go get golang.org/x/tools/cmd/cover
封面工具有两件事.
The cover tool does two things.
- 首先,当为"
go test
"赋予-cover
标志时,它将自动运行以重写包的源代码并插入检测语句.然后编译测试并照常运行,并报告基本覆盖率统计信息:
- 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 fmtcoverage.html fmt
ok fmt 0.060s coverage: 91.4% of statements
$
第二,对于更详细的报告,进行测试"的不同标志可以创建一个覆盖配置文件,然后可以使用"
go工具覆盖
"调用的覆盖程序进行分析.
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 Go(2013/09/19)的最新版本使用:
The latest versions of Go (2013/09/19) use: 运行命令可以找到有关如何生成和分析覆盖率统计信息的详细信息 Details on how to generate and analyze coverage statistics can be found by running the commands 伊凡·布莱克提到 我什至不想等待浏览器打开,所以我定义了这个别名: I don't even want to wait for the browser to open, so I defined this alias: 我只键入 That I just type 这篇关于如何在Go中衡量测试覆盖率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
go test -coverprofile <filename> <package name>
$ go help testflag
$ go tool cover -help
开始测试-coverprofile cover.out
,然后 go工具封面-html = cover.out
在默认浏览器中打开 cover.out
go test -coverprofile cover.out
and then
go tool cover -html=cover.out
opens cover.out
in your default browseralias gc=grep -v -e " 1$" cover.out
gc
,并列出了所有尚未覆盖的行的列表 (此处:带有 coverage.out
行 not 以" 1
"结尾).gc
, and have a list of all the lines not yet covered (here: with a coverage.out
line not ending with " 1
").