Coverage Stats for External Tests
In Go, it is recommended to keep tests within the same package as the code they are testing. However, if your codebase consists of numerous test files, you may prefer a cleaner organization by separating these tests into a different package. This approach restricts tests to accessing the package's public API, promoting better organization and encapsulation.
Given the following structure:
api_client: Client.go ArtistService.go api_client_tests: ArtistService.Events_test.go ArtistService.Info_test.go UtilityFunction.go
Running go test bandsintown-api/api_client_tests -cover reports 100% coverage, but this coverage only pertains to UtilityFunction.go.
Solution:
To obtain coverage statistics for the api_client package under test without merging the packages:
go test -cover -coverpkg "api_client" "api_client_tests"
However, it is worth noting that separating code and test files into different directories conflicts with the Go convention. If black-box testing is desired, where nothing outside of the package can be accessed, consider moving the tests to a new package without reorganizing the files:
api_client.go:
<code class="go">package api_client // Only accessible within the package var privateVar = 10 func Method() {}</code>
api_client_test.go:
<code class="go">package api_client_tests import "testing" func TestClient(t *testing.T) { Method() // Still accessible from another package }</code>
The above is the detailed content of How to Get Accurate Coverage Stats for External Tests in Go?. For more information, please follow other related articles on the PHP Chinese website!