avi.elkharrat
avi.elkharrat

Reputation: 6780

How to have code coverage for test packages in Go

I'm trying to generate the code coverage for my golang project.

My setup is as follows:

- my_project
|  - my_package
|  |  - my_dev_file.go
|  |  - test
|  |  |  - my_dev_file_test.go

This setup allows to test the code from the point of view of a client that would call the package, without knowing anything about its internal implementation. At the sale time, dev dirs and test dirs are clearly separated which enforces global readability of the project.

The test code looks like this:

import (
    "..."
    "testing"
    "path-to/my_package"
    "..."
)

func TestSomething(t *testing.T) {
    t.Run("should do something", func(t *testing.T) {
       my_package.MyStruct.DoSomething()

       // test something...
    })
}

This setup works fine as far as testing is concerned.

However, i can't seem to be able to generate a coverage report. Coverage is 0% whatever command i launch, starting with:

go test -coverprofile=coverage.out ./.../test
OK path-to/test       0.005s  coverage: 0.0% of statements
OK other-path-to/test 0.007s  coverage: 0.0% of statements

I'm looking for a way to generate proper code coverage without compromising the way the project is organized.

Is it possible to do so?

Upvotes: 1

Views: 1631

Answers (2)

Richar Zapata
Richar Zapata

Reputation: 11

You can try adding this flag on your command -coverpkg ./.... This is the command I use to run the tests:

go test -coverprofile coverage.out ./... -coverpkg ./...

Upvotes: 0

Grzegorz Żur
Grzegorz Żur

Reputation: 49161

You should run

go test -coverprofile=coverage.out ./...

Upvotes: 2

Related Questions