如果覆盖率低于特定百分比,则单元测试失败

Ama*_*man 3 makefile go

我制作了一个执行的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()返回的数字低于测试报告的数字.我查看了代码,函数计算的覆盖范围与测试的内部报告不同.我不确定哪个更"正确".

  • 必须编写更多的 Go 代码才能支持这一点,这似乎是倒退的。在“go test -cover”和“go tool cover”之间,您可能会认为有一种简单的方法可以从 shell 获取模块的总覆盖率。 (3认同)
  • @AlexJansen 对我来说听起来像是一个很棒的拉取请求:) (3认同)
  • 太棒了,这在逐包覆盖的基础上非常有效。有没有办法让它在包中运行所有测试,这样我就不必将 TestMain() 复制到每个包并在包的基础上设置覆盖要求。 (2认同)