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
Release: 2024-11-01 03:08:28
Original
985 people have browsed it

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
    ...
Copy after login

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"
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template