Skip to Content
Skip to content
Go Intermediate: Interfaces, Concurrency, and Services
Intermediate
Courses
Go Intermediate: Interfaces, Concurrency, and Services

Testing With Interface Fakes, t.TempDir, and testdata

Keep unit tests fast and isolated using consumer-side interfaces, auto-cleaned t.TempDir() directories, and testdata/ fixtures. After this, file and dependency tests run reliably in parallel.

Course content

Sign in to save your progress.

Course Home

Unit tests fall apart when they call a real SMTP server, write to a shared /tmp/audit.txt file that collides across parallel test runs, or embed 80-line CSV strings inline inside test functions. Instead of installing a heavy mocking framework, Go gives you three clean standard-library tools: small consumer-side interface fakes, t.TempDir(), and testdata/.

Skip ahead

If you already isolate external dependencies with small interface fakes, use t.TempDir() for scratch files, and keep read-only fixtures in testdata/, take the section quiz to complete Go Intermediate.

Experiment 1: Putting interface fakes, t.TempDir(), and testdata/ together

Suppose your store package imports a CSV file of users, writes an audit log to disk, and sends a welcome email to each user. Look how fast, isolated, and readable the unit test stays using only Go's standard library:

// 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
}

func (f *fakeMailer) Send(to, msg string) error {
	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

Experiment 2: Why testdata/ works from any directory

Notice we opened "testdata/users.csv" with a plain relative path—no hardcoded absolute path, no guessing where the repo root is! Go guarantees two special behaviors for any folder named testdata:

  • go build completely ignores testdata/ so test fixtures never bloat your production binary or trigger compile errors.
  • go test always sets each package's directory as the current working directory when running that package's tests—so "testdata/users.csv" resolves identically whether you run go test ., go test ./... from the repo root, or click Run in VS Code.

Experiment 3: Why t.TempDir() beats os.CreateTemp + manual cleanup

If two parallel tests both write to /tmp/audit.txt, one overwrites the other's file mid-test and causes random CI flakes. t.TempDir() creates a unique temporary directory per test (and per subtest!) and automatically deletes it via t.Cleanup when the test finishes—even if the test fails or panics halfway through.

Experiment 4: Writing clean test helpers with t.Helper()

When you factor repeated setup or assertions into a helper function, put t.Helper() on its first line:

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

Without t.Helper(), a failure prints the line number inside writeFixture; with t.Helper(), Go prints the exact line in your test that called writeFixture.

Common mistakes

  • Calling t.Setenv in a test that also calls t.Parallel(): Environment variables are process-wide, so Go refuses to run them together and panics immediately.
  • Writing files back into testdata/ during normal tests: Mutating committed fixture files breaks parallel tests and fails in read-only CI containers. Always write outputs into t.TempDir().
  • Over-mocking internal helper functions: Use fakes at real boundaries (email, HTTP APIs, clocks, storage)—test pure business logic directly with real inputs.

💡 Tip

Need to simulate a failing email provider? Add an err error field to fakeMailer (&fakeMailer{err: errors.New("smtp down")}) so one 10-line fake tests both success and error paths cleanly.

What happens if you skip this step

Tests tied to hardcoded /tmp paths or live external APIs flake unpredictably under go test ./...—training developers to ignore red CI builds instead of trusting them.

You run go test ./... from the repository root, and a test inside internal/store/store_test.go opens "testdata/users.csv". Which directory does Go look in for testdata/users.csv?

About

Keep unit tests fast and isolated using consumer-side interfaces, auto-cleaned t.TempDir() directories, and testdata/ fixtures. After this, file and dependency tests run reliably in parallel.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.