Test Temp Dirs With t.TempDir

Give each test its own temporary directory with t.TempDir, write fixtures there, and let the testing package remove everything on cleanup.

GoConfig Management

Code

gosnippet
40 lines
package config

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

func writeConfig(t *testing.T, dir, body string) string {
	t.Helper() // 失败时报告调用行,而不是这个辅助函数
	path := filepath.Join(dir, "config.json")
	if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
		t.Fatalf("write config: %v", err)
	}
	return path
}

func TestLoadConfigFromTempDir(t *testing.T) {
	dir := t.TempDir() // 测试结束自动递归删除
	path := writeConfig(t, dir, `{"port":8080}`)

	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read config: %v", err)
	}
	if len(data) == 0 {
		t.Fatal("config file is empty")
	}

	t.Run("isolated subtest", func(t *testing.T) {
		sub := t.TempDir() // 子测试拿到另一个独立目录
		if sub == dir {
			t.Fatal("temp dirs must differ")
		}
		other := writeConfig(t, sub, `{"port":9090}`)
		if filepath.Dir(other) != sub {
			t.Fatalf("config written outside temp dir: %s", other)
		}
	})
}

A line-by-line account

Test Temp Dirs With t.TempDir comes down to the functions writeConfig and TestLoadConfigFromTempDir.

Nothing falls through silently — 2 checkpoints test err != nil on the way through.

Applying it

Entry signature: func TestLoadConfigFromTempDir(t *testing.T)

Import TestLoadConfigFromTempDir from the file and call it — the rest of the code is implementation detail.

Statements that matter

func writeConfig(t *testing.T, dir, body string) string {
	t.Helper() // 失败时报告调用行,而不是这个辅助函数
	path := filepath.Join(dir, "config.json")
	if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
		t.Fatalf("write config: %v", err)
	}
	return path
}
if err != nil {
	t.Fatalf("read config: %v", err)
}

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `os`, `path/filepath`, `testing`. The file defines `writeConfig`, `TestLoadConfigFromTempDir` at load time.