加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 09:44:51 所属栏目:大数据 来源:网络整理
导读:有没有人成功地生成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 insta
有没有人成功地生成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”结束)。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读