英文:
"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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论