【问题标题】:No test coverage when tests are in a different package当测试在不同的包中时没有测试覆盖
【发布时间】:2018-09-25 03:27:57
【问题描述】:

我有位于单独目录中的集成测试。这些测试通过 net/http/httptest 在同一进程中运行我的 http 服务器。我的测试运行了,但没有覆盖。

为了简洁起见,这是一个非常简化的示例,不使用 http。 目录布局:

$GOPATH/src/go-test
  hello
    hello.go
  itest
    integration_test.go

hello.go

package hello

func Hello() string {
    return "hello"
}

integration_test.go

package itest

import (
    "go-test/hello"
    "testing"
)

func TestHello(t *testing.T) {
    s := hello.Hello()
    if s != "hello" {
        t.Errorf("Hello says %s", s)
    }
}

运行测试:

$ go test -v -coverpkg ./... ./itest
=== RUN   TestHello
--- PASS: TestHello (0.00s)
PASS
coverage: 0.0% of statements in ./...
ok      go-test/itest   0.001s  coverage: 0.0% of statements in ./...

另一个尝试:

$ go test -v -coverpkg all ./itest
=== RUN   TestHello
--- PASS: TestHello (0.00s)
PASS
coverage: 0.0% of statements in all
ok      go-test/itest   0.001s  coverage: 0.0% of statements in all

请注意,覆盖率为 0%。

根据go help testflag

-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 version
go version go1.10 linux/amd64

【问题讨论】:

    标签: testing go code-coverage


    【解决方案1】:
    go test -v -coverpkg ./... ./...
    

    应该会给你预期的结果

    【讨论】:

    • 这也运行了我的单元测试,这些测试都以[build failed]!?所有测试在没有-coverpkg 选项的情况下通过。
    • 没什么可继续的。我从来没有见过这个。如果你指点我一个仓库,我可以看看......
    • 失败的原因是同一个包中文件之间的循环依赖。错误消息不清楚,它也可以在没有 -coverpkg 的情况下工作,这让我感到困惑。
    • 我的所有测试也收到了[build failed] 错误。
    【解决方案2】:

    使用-coverpkg go-test/...,./...

    go-test 是 i-test 的兄弟,因此使用 ./... 不起作用,因为它只选择当前目录的包和子包。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 2018-08-06
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多