When unit testing code in different folders within a Go project, you may encounter discrepancies in code coverage reporting. This can be frustrating, as you might expect all code to be covered when running tests in the subfolders.
Problem:
Despite executing code from the stuff folder in the stuff_test folder, the coverage report shows 0% of statements covered. The following project structure is involved:
stuff/stuff.go -> package: stuff test/stuff/stuff_test.go -> package: test
Possible Cause:
The code coverage analysis is limited to the package being tested by default. In this case, the stuff_test package is in a separate folder from the stuff package, which is causing the issue.
Solution:
To resolve this, you can use the -coverpkg option when running go test. This option allows you to specify the packages for which you want to collect coverage information.
go test ./test/... -coverprofile=cover.out -coverpkg ./...
This command will apply coverage analysis to all packages that match the specified pattern, which in this case is all packages in the current directory and its subdirectories.
Viewing the Coverage Report:
Once the tests have run, you can generate a coverage report using the go tool cover command.
go tool cover -html=cover.out
This command will create an HTML report named cover.out that you can open in a web browser to view the coverage information for all the specified packages.
The above is the detailed content of Why Does My Go Code Coverage Report Show 0% When Testing Across Separate Folders?. For more information, please follow other related articles on the PHP Chinese website!