Testing Coverage in Separated Test Packages
When test files are separated into distinct packages for organizational purposes, obtaining coverage statistics for the target code can become a challenge. This question explores a workaround for this scenario, where the test package is in api_client_tests and the code is in api_client.
The Question:
How can coverage stats be accurately obtained for the api_client package under test when the associated tests are located in a separate package?
The Solution:
The provided solution involves using the go test command with the -cover and -coverpkg flags. By specifying the api_client package as the target for coverage using the -coverpkg flag:
go test -cover -coverpkg "api_client" "api_client_tests"
The coverage statistics will be generated specifically for the code in the api_client package, even though the tests are located externally in api_client_tests.
Alternative Approaches:
While the method described above is a viable solution, it deviates from the typical Go convention of keeping test files within the same package as the code they test. This can lead to difficulties in debugging and collaboration.
An alternative approach, as mentioned in the comments, is to simply move the test files into the same package as the code under test. This ensures that all the code related to a particular feature or component is grouped together for ease of maintenance.
The above is the detailed content of How to Obtain Accurate Coverage Stats for a Package When Tests Are in a Separate Package?. For more information, please follow other related articles on the PHP Chinese website!