Measuring Test Coverage in Go
Question:
How does one measure code coverage for Go unit tests?
Answer:
In Go 1.2 and later, test coverage reporting is available. To enable it:
-
Instrument Test Code: Run go test -coverprofile= to automatically rewrite and instrument test code. Test coverage statistics are then displayed.
-
Generate Coverage Profile (Optional): Use go test -coverprofile= to create a coverage profile file.
-
Analyze Coverage Profile (Optional): Run go tool cover to analyze the profile file.
Additional Features:
-
HTML Output: go tool cover -html= opens an HTML report in your default browser.
-
Coverage for Non-Test Code: As of Go 1.19, code coverage can be extended to applications through go build -cover.
-
Coverage for Integration Tests: In Go 1.20 and later, coverage can be extended to integration tests by feeding instrumented binaries into the test.
-
Package-Level Blackbox Coverage: Use go test -coverpkg= to measure coverage for a specific package during blackbox testing.
The above is the detailed content of How to Measure Code Coverage for Go Unit Tests?. For more information, please follow other related articles on the PHP Chinese website!