Home >Backend Development >Golang >How Can I Get Coverage Stats for a Package When Tests Are in a Separate Directory?

How Can I Get Coverage Stats for a Package When Tests Are in a Separate Directory?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 03:08:28969browse

How Can I Get Coverage Stats for a Package When Tests Are in a Separate Directory?

Coverage Stats for Tests in Separate Packages

When separating tests from code files into different packages, it becomes challenging to obtain coverage stats for the package under test. Consider the following directory 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 only provides coverage for the UtilityFunction.go file, leaving out the actual api_client package.

Solution:

To resolve this issue, use the following command:

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

This command allows you to run the tests with coverage measurement enabled specifically for the api_client package.

Note on Package Structure:

However, it's worth noting that splitting code files and tests into different directories is not a recommended practice in Go. Instead, keeping tests within the same package ensures that they are correctly limited to interacting with the package's public API.

Code Accessibility for Black-Box Testing:

If the goal is to perform black-box testing where private package-level variables and functions are inaccessible to tests, the following workaround can be used:

<code class="go">// 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"
import "api_client"  // import the package **without** renaming it

func TestBlackBox(t *testing.T) {
    api_client.Method()  // call the method from the "api_client" package
}</code>

This allows tests to access package-level items without modifying the directory structure or violating encapsulation rules.

The above is the detailed content of How Can I Get Coverage Stats for a Package When Tests Are in a Separate Directory?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn