SyntaxStudy
Sign Up
Go Benchmarks, Examples, and Coverage
Go Beginner 1 min read

Benchmarks, Examples, and Coverage

Go's testing package supports three types of test functions: Test functions for correctness, Benchmark functions for performance, and Example functions for documentation. Benchmark functions are named `BenchmarkXxx` and receive `*testing.B`. They run the benchmarked code `b.N` times, where the testing framework adjusts N until it gets a stable measurement. Run benchmarks with `go test -bench=. -benchmem`. Example functions are named `ExampleXxx` and serve dual purpose: they appear in the package's documentation and are verified by the testing framework to produce the expected output. The expected output is specified in a `// Output:` comment at the end of the function. If the program output does not match, the test fails, keeping documentation in sync with code. Test coverage is measured with `go test -cover` or `go test -coverprofile=coverage.out`. The coverage report shows the percentage of statements executed by tests. Visualise which lines are covered with `go tool cover -html=coverage.out`. While 100% coverage is not always practical, the tooling helps identify untested code paths. Aim for meaningful coverage of business logic and error paths.
Example
// string/string.go
package strutil

import "strings"

// Reverse returns the Unicode-correct reversal of s.
func Reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

// IsPalindrome reports whether s reads the same forwards and backwards.
func IsPalindrome(s string) bool {
    s = strings.ToLower(s)
    return s == Reverse(s)
}

// string/string_test.go
package strutil_test

import (
    "testing"

    "github.com/example/app/strutil"
)

// Example — doubles as documentation and a runnable test.
func ExampleReverse() {
    fmt.Println(strutil.Reverse("Hello, 世界"))
    // Output: 界世 ,olleH
}

// Benchmark — run with: go test -bench=BenchmarkReverse -benchmem
func BenchmarkReverse(b *testing.B) {
    s := "The quick brown fox jumps over the lazy dog"
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        strutil.Reverse(s)
    }
}

func TestIsPalindrome(t *testing.T) {
    cases := []struct {
        in   string
        want bool
    }{
        {"racecar", true},
        {"hello", false},
        {"A", true},
        {"", true},
    }
    for _, c := range cases {
        if got := strutil.IsPalindrome(c.in); got != c.want {
            t.Errorf("IsPalindrome(%q) = %v, want %v", c.in, got, c.want)
        }
    }
}