如果覆盖率低于一定百分比,则无法通过单元测试 [英] fail unit tests if coverage is below certain percentage
问题描述
我制作一个执行 go test -cover
的makefile.如果覆盖率低于X,是否有可能使 make unit_tests
命令失败?我该怎么做?
I make a makefile that executes go test -cover
. Is it possible to fail the make unit_tests
command if coverage is below X? How would I do that?
推荐答案
您可以在测试中使用 TestMain
来做到这一点.TestMain可以充当测试的自定义入口点,然后您可以调用 testing.Coverage()
来访问覆盖率统计信息.
You can use TestMain
in your test to do that. TestMain can act as a custom entry point to tests, and then you can invoke testing.Coverage()
to get access to the coverage stats.
例如,如果您希望失败率低于80%,则可以将其添加到软件包的测试文件之一:
So for example, if you want to fail at anything below 80%, you could add this to one of your package's test files:
func TestMain(m *testing.M) {
// call flag.Parse() here if TestMain uses flags
rc := m.Run()
// rc 0 means we've passed,
// and CoverMode will be non empty if run with -cover
if rc == 0 && testing.CoverMode() != "" {
c := testing.Coverage()
if c < 0.8 {
fmt.Println("Tests passed but coverage failed at", c)
rc = -1
}
}
os.Exit(rc)
}
然后 go test -cover
将调用此入口点,您将失败:
Then go test -cover
will call this entry point and you'll fail:
PASS
coverage: 63.0% of statements
Tests passed but coverage failed at 0.5862068965517241
exit status 255
FAIL github.com/xxxx/xxx 0.026s
请注意, testing.Coverage()
返回的数字低于测试报告的数字.我看过代码,该函数计算覆盖率的方式与测试内部报告的方式不同.我不确定哪个更正确".
Notice that the number that testing.Coverage()
returns is lower than what the test reports. I've looked at the code and the function calculates its coverage differently than the test's internal reporting. I'm not sure which is more "correct".
这篇关于如果覆盖率低于一定百分比,则无法通过单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!