marsevilspirit's blog

Go test visual coverage

Generating Coverage Reports in Go

Go provides a series of built-in tools that make generating coverage reports very convenient. Here’s how to use these tools.

Generating a Coverage Report

Assume you have a Go package with test files, you can generate a coverage report using the go test command.

1
go test -coverprofile=coverage.out

Here, we use the -coverprofile flag to specify the output file coverage.out. This file will contain coverage data.

Viewing the Coverage Report

After generating the coverage data, you can view the report in various formats using the go tool cover command.

  1. View Coverage Summary

    You can view a brief coverage summary:

    1
    go tool cover -func=coverage.out

    This command will display the coverage percentage of each function and the total coverage.

  2. View in HTML Format

    You can also generate an HTML format coverage report for a more intuitive view:

    1
    go tool cover -html=coverage.out -o coverage.html

    Then, you can open the coverage.html file in a browser to view a detailed coverage report.

Viewing Coverage for the Entire Project

  1. Run Tests and Generate Coverage File:

    Run the following command in your project directory, which will generate a coverage file coverage.out:

    1
    go test -coverprofile=coverage.out ./...
  2. Generate HTML Report:

    Use the go tool cover command to convert the coverage.out file to HTML format:

    1
    go tool cover -html=coverage.out -o coverage.html
  3. View HTML Report:

    Open the coverage.html file, and you can view the detailed code coverage in a browser.

Oct 2024