Go

How do you separate unit tests from slow integration tests, and what are golden files?

Question 400MediumGo 1.22 to 1.25

Options for gating slow tests:

  • testing.Short(): skip under go test -short.
  • Build constraints: //go:build integration at the top of the file; run with go test -tags=integration ./....
  • Environment gating: skip unless DATABASE_URL is set — explicit and CI-friendly.

Golden files store expected output in testdata/ (ignored by the go tool for builds) and compare against it, with a flag to regenerate. Great for code generators, templates, and CLI output.

var update = flag.Bool("update", false, "update golden files")

func TestRenderReport(t *testing.T) {
    if testing.Short() {
        t.Skip("skipping in -short mode")
    }
    got := RenderReport(sampleData())
    golden := filepath.Join("testdata", t.Name()+".golden")
    if *update {
        if err := os.WriteFile(golden, got, 0o644); err != nil {
            t.Fatal(err)
        }
    }
    want, err := os.ReadFile(golden)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(got, want) {
        t.Errorf("output mismatch; run go test -update\n%s", cmp.Diff(string(want), string(got)))
    }
}

Gotchas: review golden diffs in code review — -update can bless a bug; output must be deterministic (sort map keys, fix timestamps). Go test caching skips re-running unchanged tests; files read under testdata and env vars read via os.Getenv are tracked, but use -count=1 to force a rerun for tests that hit external systems.

More on Performance, Profiling & Testing

All 38 Performance, Profiling & Testing questions