How to Measure Code Coverage for Go Unit Tests?

Mary-Kate Olsen
Release: 2024-11-14 19:35:02
Original
306 people have browsed it

How to Measure Code Coverage for Go Unit Tests?

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:

  1. Instrument Test Code: Run go test -coverprofile= to automatically rewrite and instrument test code. Test coverage statistics are then displayed.
  2. Generate Coverage Profile (Optional): Use go test -coverprofile= to create a coverage profile file.
  3. 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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template