如何在Go中衡量测试覆盖率

编程入门 行业动态 更新时间:2024-10-27 19:29:40
本文介绍了如何在Go中衡量测试覆盖率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人成功地为Go单元测试生成了代码覆盖率吗?我在网络上找不到用于该工具的工具.

Has anyone succeeded in generating code coverage for Go unit tests? I can't find a tool for that on the web.

推荐答案

请注意, Go 1.2(2013年第四季度,可用rc1)现在将显示 测试覆盖率结果 :

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/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:

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

伊凡·布莱克提到在评论中:

开始测试-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 browser

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

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

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

我只键入 gc ,并列出了所有尚未覆盖的行的列表 (此处:带有 coverage.out 行 not 以" 1 "结尾).

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").

更多推荐

如何在Go中衡量测试覆盖率

本文发布于:2023-11-14 10:42:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:覆盖率   测试   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!