How Can I Measure Coverage for a Package with Separated Test Files in Go?

Mary-Kate Olsen
Release: 2024-10-27 20:18:30
Original
764 people have browsed it

 How Can I Measure Coverage for a Package with Separated Test Files in Go?

Testing Package Coverage with Separated Test Files

When organizing a codebase with numerous test files, it might be advantageous to separate tests from the actual codebase for clarity and adherence to best practices. In such scenarios, the test files may reside in a different package than the code under test.

One potential challenge arises when obtaining coverage statistics for the actual package under test. By default, tests only provide coverage for the package they reside in. This issue stems from Go's approach, which dictates that code and test files should coexist within the same package.

Solution

Fortunately, Go provides a solution to this dilemma:

go test -cover -coverpkg "api_client" "api_client_tests"
Copy after login

By specifying the "-coverpkg" flag, you can instruct Go to measure coverage for the specified package ("api_client" in this case), while running tests from a separate package ("api_client_tests"). This allows you to accurately ascertain the coverage of your API client package without the need to consolidate it with the test files.

Alternative Approach

While using separated test packages can provide benefits in terms of organization, it is worth noting that this approach deviates from the conventional Go way of organizing code and tests. If black-box testing is your primary objective, where only public package APIs are accessible to tests, an alternative method is available:

  1. Keep the test files within the same package as the code.
  2. Use the "internal" visibility modifier to restrict access to package-private methods and variables, ensuring that only the package's public API is exposed to tests.

The above is the detailed content of How Can I Measure Coverage for a Package with Separated Test Files 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!