当测试位于其他包装中时,无测试范围

Pet*_*hev 5 testing code-coverage go

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

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

$GOPATH/src/go-test
  hello
    hello.go
  itest
    integration_test.go
Run Code Online (Sandbox Code Playgroud)

你好

package hello

func Hello() string {
    return "hello"
}
Run Code Online (Sandbox Code Playgroud)

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

运行测试:

$ 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 ./...
Run Code Online (Sandbox Code Playgroud)

另一尝试:

$ 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
Run Code Online (Sandbox Code Playgroud)

请注意,覆盖率为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.
Run Code Online (Sandbox Code Playgroud)

当我的测试在不同的程序包中时,如何获得真实的保障?

$ go version
go version go1.10 linux/amd64
Run Code Online (Sandbox Code Playgroud)

小智 9

go test -v -coverpkg ./... ./...
Run Code Online (Sandbox Code Playgroud)

应该给你预期的结果