Standard Library

Testing

Write table-driven tests, test HTTP handlers, use subtests, and understand useful test commands.

What you will learn

  • write focused unit and table-driven tests;
  • test error meaning rather than text when possible;
  • test HTTP handlers without binding a real port;

Tests are ordinary Go functions stored in files ending with _test.go. They give you confidence to change code and help document expected behaviour.

A first unit test

Production code:

math.go
package mathx

func Add(a, b int) int {
    return a + b
}

Test code:

math_test.go
package mathx

import "testing"

func TestAdd(t *testing.T) {
    got := Add(2, 3)
    want := 5

    if got != want {
        t.Fatalf("Add(2, 3) = %d; want %d", got, want)
    }
}

Run it with:

go test ./...

./... means every package below the current directory.

Table-driven tests

Tables make several cases easy to read and extend:

func TestAdd(t *testing.T) {
    tests := []struct {
        name string
        a    int
        b    int
        want int
    }{
        {name: "positive", a: 2, b: 3, want: 5},
        {name: "negative", a: -2, b: -3, want: -5},
        {name: "zero", a: 8, b: 0, want: 8},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got := Add(tt.a, tt.b)
            if got != tt.want {
                t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.want)
            }
        })
    }
}

Test names should describe behaviour, not implementation details.

Test errors correctly

value, err := ParsePort("invalid")
if err == nil {
    t.Fatal("ParsePort() error = nil; want an error")
}

Use errors.Is or errors.As when callers depend on a specific error identity or type. Avoid matching entire error strings unless the text itself is the contract.

Test HTTP handlers

func TestStatus(t *testing.T) {
    request := httptest.NewRequest(http.MethodGet, "/status", nil)
    recorder := httptest.NewRecorder()

    status(recorder, request)

    response := recorder.Result()
    defer response.Body.Close()

    if response.StatusCode != http.StatusOK {
        t.Fatalf("status = %d; want %d", response.StatusCode, http.StatusOK)
    }
}

httptest can also start a temporary real server when you need to test client behaviour.

Useful commands

go test ./...              # all tests
go test -run TestAdd ./... # matching tests
go test -race ./...        # tests with the race detector
go test -cover ./...       # coverage summary
go test -count=1 ./...     # bypass cached successful results

Coverage shows which statements ran; it does not tell you whether the assertions are meaningful.

Test design

  • Keep tests deterministic; avoid real sleeps and public network services.
  • Inject clocks, randomness, storage, or clients when those dependencies need control.
  • Test public behaviour and important edge cases.
  • Do not mock every function. Small real values are often clearer than large mock frameworks.
  • A bug fix should usually include a test that fails before the fix.

Practice

Test the lesson API from the HTTP guide. Cover a successful request, malformed JSON, missing required fields, and an unsupported method. Run the tests with the race detector.

Summary

  • Tests document observable contracts and protect changes.
  • Table-driven tests make related cases easy to extend.
  • Test outcomes and error identity, avoiding irrelevant implementation detail.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026