“go test”报告了错误的语句覆盖率。

huangapple go评论94阅读模式
英文:

"go test" reports incorrect statement coverage

问题

我有一个只有两个Go文件的:一个定义了主函数,另一个用于测试。

现在假设我已经进入了这个包,并运行了以下命令:

$ go test -cover
PASS
coverage: 41.8% of statements
ok      github.com/suzaku/dummage       0.010s

如你所见,这个命令正常工作。

但是我想生成一个HTML报告,所以经过一些搜索,我使用了以下命令:

$ go test -run=Coverage -coverprofile=c.out github.com/suzaku/dummage
ok      github.com/suzaku/dummage       0.010s  coverage: 1.8% of statements

注意,这次覆盖率下降到了1.8%。

我该怎么解决这个问题?

英文:

I have a package with only two Go file: one defines the main function and the other is for the tests.

Now assume that I have cd into this package and run the following command:

$ go test -cover
PASS
coverage: 41.8% of statements
ok      github.com/suzaku/dummage       0.010s

As you can see, this works correctly.

But I want to generate a HTML report, so after some googling I use the following command:

$ go test -run=Coverage -coverprofile=c.out github.com/suzaku/dummage
ok      github.com/suzaku/dummage       0.010s  coverage: 1.8% of statements

Note that this time the coverage drops to 1.8%.

What can I do to fix this?

答案1

得分: 3

你确定在go test中需要那个-run=Coverage标志吗?这意味着它只会运行与Coverage匹配的测试。如果你只想为那些测试生成一个覆盖率文件,可以运行go test -coverprofile c.out github.com/suzaku/dummage。然后你可以运行go tool cover -html c.out来查看HTML报告。

如果你有意添加了-run=Coverage,那么这是预期的行为-在-run=Coverage期间运行的代码量要比运行所有测试时少得多,并且测试覆盖率是针对整个包计算的。

英文:

Are you sure you need that -run=Coverage flag in your go test? This means it will only run tests that match Coverage. If you just want to generate a cover profile for that tests, run go test -coverprofile c.out github.com/suzaku/dummage. Then you may run go tool cover -html c.out to see the HTML report.

If you added -run=Coverage on purpose, then it's expected behavior - the amount of code that runs during -run=Coverage is much less than while running all tests, and the test coverage is calculated for the entire package.

huangapple
  • 本文由 发表于 2016年3月19日 21:34:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/36102417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定