问题
I have integration tests which are located in a separate directory. Those tests run my http server in the same process via net/http/httptest. My tests run but I get no coverage.
Here is a very simplified example not using http for brevity. Directory layout:
$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)
}
}
Run the test:
$ 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 ./...
Another attempt:
$ 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
Notice that coverage is 0%.
According to 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.
How can I get the real coverage when my tests are in a different package?
$ go version
go version go1.10 linux/amd64
回答1:
go test -v -coverpkg ./... ./...
should give you the expected results
回答2:
use -coverpkg go-test/...,./...
go-test is a sibling to i-test, consequently using ./... does not work, as it only selects packages and subpackages of the current directory.
来源:https://stackoverflow.com/questions/49839543/no-test-coverage-when-tests-are-in-a-different-package