8

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?

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Nathan Cooper
  • 6,262
  • 4
  • 36
  • 75
  • Additionally, I'm assuming it's a mistake of mine not to instead use `UtilityFunction_test.go`, even though it contains no tests, because it confuses the coverage? – Nathan Cooper May 26 '16 at 14:46
  • I'm going to go track down some opinions on where to put tests. I read to seperate packages [here](https://medium.com/@matryer/5-simple-tips-and-tricks-for-writing-unit-tests-in-golang-619653f90742#.arh8p92aq). But if it's just flagrently wrong and anti-idomatic for go feel free to point that out here. I've also seen it aclaimed as valid on [Proper package naming for testing in Go Lang](http://stackoverflow.com/a/31443271/1734730) – Nathan Cooper May 26 '16 at 14:55
  • If you want to test the exported interface of `package api` only your test typically live in `package api_test` but the files are kept in the same folder (here api_client) and coverage should work. I never saw this separation into two different folders. – Volker May 26 '16 at 15:06
  • Try with -cover -coverpkg "api_client" "api_client_tests" – PerroVerd May 26 '16 at 16:00

1 Answers1

9

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()
}
Oleg Kovalov
  • 734
  • 11
  • 33