Skip to content

Go Test Cover Profile

DodaTech 1 min read

In this tutorial, you'll learn about Go Test: Coverage Profile. We cover key concepts, practical examples, and best practices.

Test coverage -- Measure and visualize Go test coverage using -coverprofile and go tool cover.

The Problem

Go's testing package can generate coverage profiles showing which lines are tested. Use -coverprofile flag and go tool cover for HTML visualization.

Wrong

go test -v ./...

Output:

// Tests pass or fail, but no coverage info
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out -o coverage.html

Output:

// coverage.html shows green/red for covered/uncovered lines

Prevention

  • Use -coverprofile to generate coverage data
  • go tool cover -html generates visual report
  • Use -covermode=count for execution counts
  • Use -coverpkg=./... to measure all packages
  • Target 80%+ coverage for critical packages

Common Mistakes with test cover profile

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [Char] with poor performance for large text operations

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What is the default coverage mode?**

set (boolean: covered or not). Use -covermode=count for call counts.

How to exclude generated code from coverage?

Use //go:build !test or set -coverpkg selectively.

Can I enforce coverage thresholds?

Use third-party tools or custom script checking go tool cover output.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro