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"
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:
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!