Skip to Content
Skip to content
Write Clean Go Tests With Interface Fakes, t.TempDir, and testdata
Intermediate
Tutorials

Write Clean Go Tests With Interface Fakes, t.TempDir, and testdata

Replace external dependencies with small consumer-side interface fakes, use t.TempDir() for scratch files, and load fixtures from testdata/. After this, tests stay fast and parallel-safe.

Updated 4 min read GoTesting and Debugging

Skip ahead

Already isolating external dependencies with 1-method interfaces and t.TempDir()? Jump to Case 3: simulating provider errors or Case 4: writing clean helpers with t.Helper().

Go unit tests slow down and flake for three predictable reasons: calling a live external service (SMTP, S3, or Stripe), writing temporary files to a shared path like /tmp/audit.txt that collides when t.Parallel() runs, or stuffing 80-line CSV/JSON strings inline inside test files.

You do not need a third-party mocking framework to fix any of those. Go's standard library gives you three clean conventions: small consumer-side interface fakes, t.TempDir(), and testdata/. Verified on Go 1.27.

Case 1: Combine an interface fake, t.TempDir(), and testdata/

Suppose your store package reads a CSV of new users, writes an audit file to disk, and emails each user via a Mailer. Put the CSV fixture in testdata/users.csv (next to your package), write outputs into t.TempDir(), and pass a 6-line in-memory fakeMailer:

// testdata/users.csv
alice,admin
bob,viewer
// store_test.go
package store

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

type Mailer interface {
	Send(to, msg string) error
}

type fakeMailer struct {
	sent []string
	err  error
}

func (f *fakeMailer) Send(to, msg string) error {
	if f.err != nil {
		return f.err
	}
	f.sent = append(f.sent, to+":"+msg)
	return nil
}

func TestSaveAndNotify(t *testing.T) {
	raw, err := os.ReadFile("testdata/users.csv")
	if err != nil {
		t.Fatal(err)
	}
	dir := t.TempDir()
	outPath := filepath.Join(dir, "audit.txt")
	if err := os.WriteFile(outPath, raw, 0o600); err != nil {
		t.Fatal(err)
	}
	m := &fakeMailer{}
	for line := range strings.SplitSeq(strings.TrimSpace(string(raw)), "\n") {
		_ = m.Send(strings.Split(line, ",")[0], "imported")
	}
	if len(m.sent) != 2 {
		t.Fatalf("got %d, want 2", len(m.sent))
	}
}
$ go test -v .
=== RUN   TestSaveAndNotify
--- PASS: TestSaveAndNotify (0.00s)
PASS
ok  	example.com/testdoubles	0.001s

Case 2: Why testdata/ works whether you run go test . or go test ./...

Developers moving from Python or Node often worry that a relative path like "testdata/users.csv" will break when CI runs go test ./... from the repository root. In Go, two toolchain rules guarantee it always works:

  • go test always sets each package's own directory as the working directory before running that package's tests.
  • go build completely ignores any directory named testdata, so fixture files never get compiled or bloat your production binary.

Case 3: Simulating downstream failures without extra frameworks

Because fakeMailer is a plain struct with an optional err error field, testing how your importer handles an SMTP outage takes two lines—no mock-expectation DSL required:

m := &fakeMailer{err: errors.New("smtp connection refused")}
err := importUsers(m, "testdata/users.csv")
if err == nil {
	t.Fatal("expected error when mailer fails, got nil")
}

And because t.TempDir() creates a unique directory per test (and per t.Run subtest!) and deletes it automatically via t.Cleanup even on t.Fatal, you can safely call t.Parallel() across dozens of file tests without path collisions or leftover temp files.

Case 4: Reporting the caller's line number with t.Helper()

When several tests need to write scratch files into t.TempDir(), extract a helper and put t.Helper() on its first line:

func writeTempFile(t *testing.T, dir, name, content string) string {
	t.Helper()
	p := filepath.Join(dir, name)
	if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
		t.Fatal(err)
	}
	return p
}

Without t.Helper(), a failure points to the line inside writeTempFile; with t.Helper(), Go points directly to the calling line inside your test.

💡 Tip

Define your Mailer interface inside the consumer package (the package doing the importing), not inside the SMTP client package. Keeping interfaces 1–2 methods wide makes fakes trivial to write and maintain.

Common mistakes

  • Writing to hardcoded /tmp/test.csv paths: Collides immediately under t.Parallel() or concurrent CI jobs; always use t.TempDir().
  • Modifying files inside testdata/ during test runs: Breaks parallel tests and fails on read-only CI checkouts. Treat testdata/ as strictly read-only unless an explicit -update golden-file flag is passed.
  • Combining t.Setenv with t.Parallel(): Environment variables are process-wide, so Go panics immediately if a parallel test calls t.Setenv.

⚠ Warning

Do not mock every internal function in a package. Use interface fakes only at real I/O boundaries (email, HTTP APIs, clocks, storage); test pure logic directly with real values so refactoring internals doesn't break brittle mock expectations.

What happens if you skip this

Tests wired to live external services or shared /tmp paths flake unpredictably in CI, slow down local feedback loops, and train teams to ignore failing test runs.

Related course: Go Intermediate.

About

Replace external dependencies with small consumer-side interface fakes, use t.TempDir() for scratch files, and load fixtures from testdata/. After this, tests stay fast and parallel-safe.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
4 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.