如何测量Golang中的代码覆盖率? [英] How to measure code coverage in Golang?

查看:773
本文介绍了如何测量Golang中的代码覆盖率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人成功为Go单元测试生成代码覆盖率?我无法在网上找到该工具。

注意, .google.com / p / go / downloads / list?can = 2rel =noreferrer> Go 1.2(2013年第四季度,rc1可用)现在将显示 测试覆盖率结果


go test 的一个主要新功能是现在可以计算,并且在新的单独安装的 go tool cover 程序,显示测试覆盖率结果
$ b

覆盖工具是 go的一部分。工具 subrepository 。它可以通过运行安装



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




封面工具可以做两件事。


  • 首先,当给出 go test 时, -cover 标志,它会自动运行以重写软件包的源代码并插入检测语句。然后测试将像往常一样编译并运行,并报告基本覆盖率统计信息:



  $ go test -coverprofile fmt 
ok fmt 0.060s覆盖率:报表的91.4%
$




其次,对于更详细的报告,不同的标记为go test可以创建覆盖配置文件,覆盖程序使用<$ c $ b> b
$ b

> >,然后可以进行分析。 /stackoverflow.com/users/10259/frank-shearar\">Frank Shearar 提及



  go test -coverprofile< filename> <包名称> 




有关如何生成和分析覆盖率统计信息的详细信息,可以通过运行命令



  $ go help testflag 
$ go tool cover -help






Ivan Black 提及 in评论


go test -coverprofile cover.out 和那么

去工具封面-html = cover.out -o cover.html 打开 cover.html in browser


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

 别名gc = grep -v -e1 $coverage.out 

我只需输入 gc ,并列出所有行 coverage.out 行 not 结尾为< 1 c $ c>)。


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:

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 go.tools subrepository. 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 mentions in the comments:

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

I don't even want to wait for the browser to open, so I defined this alias:

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

That I just type gc, and have a list of all the lines not yet covered (here: with a coverage.out line not ending with " 1").

这篇关于如何测量Golang中的代码覆盖率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆