BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Test Coverage

Go 1.23

Ensure code quality by measuring Test Coverage. This example explains how to use Go's testing tools to generate coverage reports, helping you identify untested code paths and improve the reliability of your application.

Code

// main_test.go
package main

import (
    "testing"
)

func Abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

func TestAbs(t *testing.T) {
    got := Abs(-1)
    if got != 1 {
        t.Errorf("Abs(-1) = %d; want 1", got)
    }
}

// Run with: go test -cover
// To see coverage profile:
// go test -coverprofile=coverage.out
// go tool cover -html=coverage.out

Explanation

Test coverage measures the percentage of your code executed during tests. It's a critical metric for assessing test suite quality, though 100% coverage shouldn't be the only goal.

Tools for coverage analysis:

  • Summary: Run go test -cover for a quick percentage.
  • Profile: Run go test -coverprofile=c.out to generate a detailed report.
  • Visualization: Run go tool cover -html=c.out to open a browser view showing exactly which lines are covered (green) and uncovered (red). This is invaluable for finding gaps in your tests.

Code Breakdown

22
Running 'go test -cover' prints a summary of coverage percentage to the console (e.g., "coverage: 80.0% of statements").
24
The -coverprofile=coverage.out flag saves detailed coverage data to a file named 'coverage.out'. This file contains counts of how many times each statement was executed.
25
The 'go tool cover -html=coverage.out' command parses the profile and opens a visual HTML report in your default web browser. Green lines are covered, red lines are uncovered.