"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Achieve Accurate Go Code Coverage for Isolated Packages?

How to Achieve Accurate Go Code Coverage for Isolated Packages?

Posted on 2025-03-22
Browse:843

How to Achieve Accurate Go Code Coverage for Isolated Packages?

How to Measure Code Coverage of Isolated Folders in Go

In Go, measuring code coverage for packages residing in separate folders can prove challenging. Consider the following project structure:

stuff/stuff.go -> package: stuff
test/stuff/stuff_test.go -> package: test

Even though stuff_test.go executes code from stuff.go, the coverage report may indicate:

coverage: 0.0% of statements

This is because go test -cover by default analyzes only the package being tested, not its dependencies.

To address this issue, you can use the -coverpkg option to specify which packages should be considered for coverage analysis. For example, the following command will include all packages under the current directory:

go test ./test/... -coverprofile=cover.out -coverpkg ./...

Once the test execution is complete, you can generate a coverage report using:

go tool cover -html=cover.out

This will provide a detailed report of the code coverage for your project, including the coverage of packages in separate folders.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3