【问题标题】:Go: Wrong coverage when there is no tests for a packageGo:没有对包进行测试时的错误覆盖率
【发布时间】:2023-03-09 16:46:01
【问题描述】:

我有一个具有以下结构的 Go 项目:

foo/foo.go
foo/foo_test.go
main.go

如您所见,main.go 没有测试。

我使用以下命令收集覆盖率报告:

go test ./foo ./ -coverprofile=coverage.txt -covermode=atomic

这里./foo./ 显示在哪里查找包。

问题:我将覆盖率报告发送到 codecov.io,这表明我的代码 100% 被测试覆盖。但这不是真的,因为我的main.go 根本没有测试。

系统似乎只计算那些明确指定测试文件的包。

问题:如何修正覆盖率报告以计算未测试包的信息?

注意:你可以在GitHub找到我的项目,真实的统计是here。该项目具有不同的结构,但问题仍然存在(覆盖错误)。

【问题讨论】:

  • 这能解决您的问题吗? go test -coverpkg=.,./foo -coverprofile=coverage.txt -covermode=atomic . ./foo

标签: go code-coverage codecov go-testing


【解决方案1】:

-coverpkg 标志可用于指定用作覆盖分析基础的包。

引用Command go: Testing flags:

-coverpkg pattern1,pattern2,pattern3
    Apply coverage analysis in each test to packages matching the patterns.
    The default is for each test to analyze only the package being tested.
    See 'go help packages' for a description of package patterns.
    Sets -cover.

所以在你的具体例子中,这会做到:

go test -coverpkg=.,./foo -coverprofile=coverage.txt -covermode=atomic . ./foo

要将其应用于完整的模块/项目,您可以使用:

go test -coverpkg=./... -coverprofile=coverage.txt -covermode=atomic ./...

另一种选择是将“空”测试文件放入当前没有测试文件的包的文件夹中。这样一来,它们自然会被包含在默认覆盖分析中,但显然它们不会覆盖任何内容。

见github上的相关讨论:

cmd/go: go test -cover & go test -coverprofile should always output a coverage #24570

【讨论】:

  • 很遗憾,coverpkg 方法存在问题。如果你想要准确的覆盖率,你必须在没有测试的地方放置空的测试文件。我有一个 repo,展示了可用解决方法的优缺点here
【解决方案2】:

试试这个:

go test -coverpkg=./... -race -coverprofile=coverage.txt -covermode=atomic ./..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2016-05-04
    • 2018-08-06
    • 2018-09-25
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    相关资源
    最近更新 更多