Peter Dotchev
Peter Dotchev

Reputation: 3068

No test coverage when tests are in a different package

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

Upvotes: 13

Views: 5342

Answers (2)

StevieB
StevieB

Reputation: 1000

go test -v -coverpkg ./... ./...

should give you the expected results

Upvotes: 15

MTvB
MTvB

Reputation: 144

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.

Upvotes: -1

Related Questions