Search code examples
unit-testinggocode-coverage

Get Coverage stats when tests are in another package


My tests aren't in the same package as my code. I find this a less cluttered way of organising a codebase with a lot of test files, and I've read that it's a good idea in order to limit tests to interacting via the package's public api.

So it looks something like this:

api_client:
    Client.go
    ArtistService.go
    ...
api_client_tests
    ArtistService.Events_test.go
    ArtistService.Info_test.go
    UtilityFunction.go
    ...

I can type go test bandsintown-api/api_client_tests -cover and see 0.181s coverage: 100.0% of statements. But that's actually just coverage over my UtilityFunction.go (as I say when I ran go test bandsintown-api/api_client_tests -cover=cover.out and go tool cover -html=cover.out).

Is there any way to get the coverage for the actual api_client package under test, without bringing it all into the same package?


Solution

  • As it is mentioned in comments you can run

    go test -cover -coverpkg "api_client" "api_client_tests"

    to run the tests with coverage.

    But splitting code files from tests files to a different directories isn't a Go's way.

    I suppose that you want to have a black-box testing(nothing package-private stuff can be accessible outside, even for tests).

    To accomplish this it's allowed to have tests in another package(without moving the files). Example:

    api_client.go

    package api_client
    
    // will not be accessible outside of the package
    var privateVar = 10
    
    func Method() {
    }
    

    api_client_test.go

    package api_client_tests
    
    import "testing"
    
    func TestClient(t *testing.T) {
        Method()
    }