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 undergo test -short.- Build constraints:
//go:build integrationat the top of the file; run withgo test -tags=integration ./.... - Environment gating: skip unless
DATABASE_URLis 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
- Q398How can you convert between []byte and string without allocating? When is it safe?
- Q399How does the race detector work, what does it cost, and what are its limits?
- Q401What are Example functions, and how are they verified?
- Q402Walk through how you would investigate a service whose p99 latency doubled after a deploy.
- Q403How do you write a test that fails if a hot path starts allocating? Explain testing.AllocsPerRun and its caveats.
- Q404How do you benchmark concurrent code with b.RunParallel, and why does sync.RWMutex often fail to scale for read-heavy workloads?