Home >Backend Development >Golang >How Can I Get Accurate Go Code Coverage Across Separate Folders?

How Can I Get Accurate Go Code Coverage Across Separate Folders?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 15:29:09455browse

How Can I Get Accurate Go Code Coverage Across Separate Folders?

Detecting Code Coverage Across Separate Folders in Golang

In a project with a structure like:

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

when executing stuff_test, code coverage for stuff.go reports as 0.0%. While moving *_test.go into the stuff folder solves the issue, it raises questions about the project structure and Go best practices.

Solution via -coverpkg Flag

To address this situation without modifying the project structure, utilize the -coverpkg flag. This flag allows specifying the packages to include in the coverage analysis.

For the given project structure, the command becomes:

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

This command analyzes all tests in the ./test/... path for coverage information, including packages matching ./....

Generating and Viewing the Coverage Report

Once the tests are executed, use go tool cover to generate a coverage report:

go tool cover -html=cover.out

This creates an HTML report detailing the coverage information for the analyzed packages, providing insights into code coverage across the project's folders.

The above is the detailed content of How Can I Get Accurate Go Code Coverage Across Separate Folders?. 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