Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 945
Peter Dotchev Avatar asked Apr 15 '18 07:04

Peter Dotchev


People also ask

Is it possible to have 100% testing coverage explain why or why not?

100% test coverage simply means you've written a sufficient amount of tests to cover every line of code in your application. That's it, nothing more, nothing less. If you've structured your tests correctly, this would theoretically mean you can predict what some input would do to get some output.

Should tests be in the same package Golang?

Test Files and Test PackagesWithin a single folder, all Go files must be in the same package. The one exception is test files: those with a _test.go suffix. There is a really good reason for that: your test files should always be in a different package.

Do you ensure test coverage?

Test coverage is defined as a technique which determines whether our test cases are actually covering the application code and how much code is exercised when we run those test cases. If there are 10 requirements and 100 tests created and if 90 tests are executed then test coverage is 90%.


1 Answers

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

should give you the expected results

like image 119
StevieB Avatar answered Oct 09 '22 23:10

StevieB