Home >Backend Development >Golang >How to Achieve Accurate Go Code Coverage for Isolated Packages?

How to Achieve Accurate Go Code Coverage for Isolated Packages?

Linda Hamilton
Linda HamiltonOriginal
2024-11-27 06:09:09621browse

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.

The above is the detailed content of How to Achieve Accurate Go Code Coverage for Isolated Packages?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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