Advanced Go

Advanced Testing and Fuzzing

Control dependencies, test properties and boundaries, fuzz parsers, and keep suites deterministic.

What you will learn

By the end of this lesson, you will be able to:

  • make time, randomness, storage, and network boundaries controllable;
  • choose fakes, integration tests, or real dependencies deliberately;
  • write safe parallel tests and reliable cleanup;
  • fuzz an input boundary with useful seed cases and properties;
  • understand what the race detector can and cannot prove.

Test behaviour at the smallest useful boundary

A unit test should isolate a meaningful behaviour, not every function call. An integration test should cross a boundary whose real implementation matters.

Examples:

  • business rule with an in-memory fake repository: unit test;
  • SQL query and scan mapping against the target database: integration test;
  • complete HTTP route through middleware and repository: service-level test.

Use several layers. No single test style replaces the others.

Make dependencies explicit

Time-dependent code becomes deterministic when the clock is an input:

type Clock interface {
    Now() time.Time
}

type realClock struct{}

func (realClock) Now() time.Time { return time.Now() }

For a small need, a function may be enough:

type Now func() time.Time

Do not introduce a large interface when one function describes the dependency.

Fakes versus mocks

A fake implements behaviour with a simpler mechanism, such as an in-memory map. A mock commonly verifies expected interactions.

Prefer state or result assertions when possible. Tests that specify every internal call become fragile during harmless refactoring.

Use interaction assertions when the interaction itself is the contract—for example, an audit event must be written exactly once after a successful change.

Cleanup belongs to the test

func TestRepository(t *testing.T) {
    directory := t.TempDir()
    t.Setenv("APP_ENV", "test")

    resource := openTestResource(t, directory)
    t.Cleanup(func() {
        if err := resource.Close(); err != nil {
            t.Errorf("close resource: %v", err)
        }
    })
}

TempDir, Setenv, and Cleanup make ownership visible. Do not use Setenv in a test that runs in parallel because environment variables are process-global.

Parallel tests

Call t.Parallel() only when the test and its subtests do not share mutable process-global state, ports, environment, database rows, or fixed files.

Give each case isolated inputs and resource names. The current Go language gives each iteration variable created by a for loop its own iteration value under modern module language versions, but explicit case parameters can still make intent clearer and help older codebases.

Parallelism is a test performance tool, not a correctness requirement.

Golden files

A golden file stores expected complex output. It can be useful for generated code, formatted documents, or stable protocol output.

  • Keep reviewable files under testdata.
  • Normalise nondeterministic timestamps, IDs, and paths.
  • Make updates an explicit developer action.
  • Review golden diffs as carefully as source code.

Never let normal test execution silently replace expected output.

Fuzz properties, not random output

A fuzz test supplies seed inputs and a property that must always hold:

func FuzzParseLessonID(f *testing.F) {
    f.Add("lesson-42")
    f.Add("")
    f.Add("lesson-世界")

    f.Fuzz(func(t *testing.T, input string) {
        id, err := ParseLessonID(input)
        if err != nil {
            return
        }

        encoded := id.String()
        parsedAgain, err := ParseLessonID(encoded)
        if err != nil {
            t.Fatalf("valid output did not parse: %v", err)
        }
        if parsedAgain != id {
            t.Fatalf("round trip changed ID: %q -> %q", id, parsedAgain)
        }
    })
}

Run seed inputs as normal tests with go test. Start active fuzzing with a command such as:

go test -fuzz=FuzzParseLessonID -fuzztime=30s ./internal/lesson

Fuzzing writes minimised failing inputs into the seed corpus so normal future tests reproduce them. Do not fuzz code that causes uncontrolled network, filesystem, process, or resource side effects.

Race detection

go test -race ./...

The race detector reports races that occur in executed paths on supported platforms. A clean run does not prove a program has no races. Improve coverage of concurrent behaviour and combine the tool with clear ownership and synchronization.

Race-enabled builds have substantial overhead and are normally used in tests, CI, staging, or selected diagnostic environments rather than every production process.

Integration tests

Use the real database engine when SQL dialect, constraints, transactions, or driver behaviour matters. Create isolated schemas/databases or unique records per test, and make setup/cleanup deterministic.

Avoid making every unit test start heavy infrastructure. Keep a fast core suite and a clearly invoked integration suite.

Common mistakes

  • Mocking implementation details: harmless refactoring breaks many tests.
  • Using real time and sleep: tests become slow and flaky.
  • Sharing one mutable fake across parallel tests: tests race and contaminate each other.
  • Fuzzing without a property: “did not panic” may be useful but often misses semantic corruption.
  • Assuming race detection is a proof: unexecuted paths remain unobserved.
  • Using a different database for convenience: engine-specific production behaviour is never tested.

Practice

Fuzz a parser for a comma-separated list of lesson IDs. The parser must never panic, must reject empty items, must enforce an item limit, and must round-trip every accepted list through its formatter.

Summary

  • Test at unit, integration, and service boundaries according to the behaviour being verified.
  • Make time and other nondeterministic dependencies explicit.
  • Prefer behaviour assertions over exhaustive internal-call expectations.
  • Fuzz stable properties at bounded input boundaries.
  • Race detection observes executed races; sound ownership remains essential.

Official reference: Go fuzzing.

Ready to wrap up?

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

Copyright © 2026