Writing Tests in Go: Unit Tests, Examples, and Benchmarks

Unit Testing

Basic Srtucture

Test functions must begin with Test and accept a single parameter t *testing.T. Use assertion methods from *testing.T to verify results. Execute tests using the go test command.

Example Implementation

package calculator

import "testing"

func Greet() string {
    return "Welcome, user"
}

func TestGreeting(t *testing.T) {
    result := Greet()
    expected := "Welcome, user"

    if result != expected {
        t.Fatalf("Received '%s' but expected '%s'", result, expected)
    }
}

func TestGreetingWithName(t *testing.T) {
    validateOutput := func(t *testing.T, actual, desired string) {
        t.Helper()
        if actual != desired {
            t.Fatalf("Received '%s' but expected '%s'", actual, desired)
        }
    }

    t.Run("greeting with specific name", func(t *testing.T) {
        output := Greet("Alex")
        expected := "Welcome, Alex"
        validateOutput(t, output, expected)
    })

    t.Run("default greeting for empty input", func(t *testing.T) {
        output := Greet("")
        expected := "Welcome, Guest"
        validateOutput(t, output, expected)
    })
}

Common Testing Methods

  • t.Errorf(): Reports test failure with formatted message
  • t.Run(): Executtes a named subtest
  • t.Helper(): Marks function as test helper for better error reporting

Example Functions

Structure and Usage

Example functions start with Example and validate output using // Output: comments. Without this comment, examples compile but don't execute during testing.

Implementation Example

func Multiply(a, b int) int {
    return a * b
}

func ExampleMultiply() {
    product := Multiply(3, 4)
    fmt.Println(product)
    // Output: 12
}

Benchmark Testing

Overview

Benchmark functions measure code performance by executing code b.N times, where b.N is automatically adjusted for reliable measurements.

Benchmark Implementation

package stringutils

import "testing"

func Duplicate(text string) string {
    var output string
    for count := 0; count < 5; count++ {
        output += text
    }
    return output
}

func BenchmarkDuplicate(b *testing.B) {
    for iteration := 0; iteration < b.N; iteration++ {
        Duplicate("x")
    }
}

Benchmark Control Methods

  • b.StopTimer(): Pauses timing measurements
  • b.StartTimer(): Resumes timing measurements
  • b.ResetTimer(): Clears accumulated timing data

Runing Benchmarks

Execute with:

go test -bench ^BenchmarkDuplicate$ ./utils

Sample output:

goos: linux
goarch: amd64
pkg: github.com/user/project/utils
BenchmarkDuplicate-16    15864240    68.45 ns/op    24 B/op    6 allocs/op
PASS
ok      github.com/user/project/utils    1.892s

Tags: Go testing benchmark unit-testing Golang

Posted on Tue, 22 Sep 2026 16:07:14 +0000 by D