How to Get Accurate Coverage Stats for External Tests in Go?

Patricia Arquette
Release: 2024-10-27 16:02:29
Original
185 people have browsed it

 How to Get Accurate Coverage Stats for External Tests in Go?

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

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!