0
0
GoHow-ToBeginner · 3 min read

How to Use Test Coverage in Go: Simple Guide

In Go, use the go test -cover command to measure test coverage of your code. This shows the percentage of code tested and helps find untested parts. For detailed reports, use go test -coverprofile=coverage.out and then go tool cover -html=coverage.out to see coverage visually.
📐

Syntax

The basic command to check test coverage in Go is go test -cover. You can add options like -coverprofile=filename to save coverage data to a file. Then use go tool cover -html=filename to open a detailed coverage report in your browser.

  • go test: runs tests
  • -cover: shows coverage percentage
  • -coverprofile=filename: saves coverage data
  • go tool cover -html=filename: shows coverage visually
bash
go test -cover

go test -coverprofile=coverage.out

go tool cover -html=coverage.out
💻

Example

This example shows a simple Go package with a function and its test. Running go test -cover reports the coverage percentage. Saving coverage to a file and opening it visually helps see which lines are tested.

go
package mathutil

// Add returns the sum of two integers.
func Add(a, b int) int {
    return a + b
}

// mathutil_test.go
package mathutil

import "testing"

func TestAdd(t *testing.T) {
    got := Add(2, 3)
    want := 5
    if got != want {
        t.Errorf("Add(2, 3) = %d; want %d", got, want)
    }
}

// Run coverage commands in terminal:
// go test -cover
// go test -coverprofile=coverage.out
// go tool cover -html=coverage.out
Output
PASS coverage: 100.0% of statements ok mathutil 0.001s
⚠️

Common Pitfalls

Common mistakes when using test coverage in Go include:

  • Not running tests before checking coverage, so no data is generated.
  • Forgetting to use -coverprofile to save detailed coverage data.
  • Misinterpreting coverage percentage as code quality; 100% coverage doesn't guarantee bug-free code.
  • Running coverage on packages without tests returns 0% coverage.

Always write meaningful tests and use coverage as a guide, not a goal.

bash
/* Wrong way: No tests written, coverage shows 0% */
// No test file present

/* Right way: Write tests and run coverage */
// go test -cover
// go test -coverprofile=coverage.out
// go tool cover -html=coverage.out
📊

Quick Reference

CommandDescription
go test -coverRun tests and show coverage percentage
go test -coverprofile=coverage.outSave coverage data to a file
go tool cover -html=coverage.outOpen detailed coverage report in browser
go test ./...Run tests in all subdirectories (useful for big projects)

Key Takeaways

Use go test -cover to quickly see test coverage percentage.
Save coverage data with -coverprofile and view it visually with go tool cover -html.
Coverage helps find untested code but does not guarantee code correctness.
Write meaningful tests before measuring coverage for useful results.
Run coverage on all packages with go test ./... for full project insight.