我制作了一个执行的makefile go test -cover.make unit_tests如果覆盖率低于X,是否可能使命令失败?我该怎么办?
Not*_*fer 11
您可以TestMain在测试中使用它来执行此操作.TestMain可以作为测试的自定义入口点,然后您可以调用testing.Coverage()以访问coverage统计信息.
因此,例如,如果您希望在低于80%的任何值时失败,您可以将其添加到您的某个包的测试文件中:
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)
}
Run Code Online (Sandbox Code Playgroud)
然后go test -cover将调用此入口点,您将失败:
PASS
coverage: 63.0% of statements
Tests passed but coverage failed at 0.5862068965517241
exit status 255
FAIL github.com/xxxx/xxx 0.026s
Run Code Online (Sandbox Code Playgroud)
请注意,testing.Coverage()返回的数字低于测试报告的数字.我查看了代码,函数计算的覆盖范围与测试的内部报告不同.我不确定哪个更"正确".