Use temporary fixtures and test doubles
Use temporary fixtures and test doubles
A fixture is controlled test data or state. t.TempDir creates a unique temporary directory and arranges its removal after the test. A test double replaces a real dependency with a controlled implementation. Prefer a small interface that describes what the caller needs; avoid external services in unit tests.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
import "os"
func Load(path string) (string, error) { b, e := os.ReadFile(path); return string(b), e }
--- calc_test.go ---package calc
import ( "os" "path/filepath" "testing")
func TestLoad(t *testing.T) { p := filepath.Join(t.TempDir(), "note.txt") if err := os.WriteFile(p, []byte("hello"), 0600); err != nil { t.Fatal(err) } got, err := Load(p) if err != nil || got != "hello" { t.Fatalf("got %q, err %v", got, err) }}WriteFile creates only a file inside the test directory; check setup errors before testing Load. The test checks both returned content and error. File paths and cleanup stay local to the test. This is a local filesystem test, not a pure in-memory unit test.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLoadInject a controlled dependency
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
type PriceSource interface{ Price() int }
func Total(s PriceSource, n int) int { return s.Price() * n }
--- calc_test.go ---package calc
import "testing"
type fixedPrice int
func (p fixedPrice) Price() int { return int(p) }func TestTotal(t *testing.T) { if got := Total(fixedPrice(7), 3); got != 21 { t.Errorf("got %d", got) }}fixedPrice supplies a predictable price without contacting any service. It implements the same interface implicitly. The test checks Total, not the behavior of a real pricing service. Add integration tests for real dependency contracts separately.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestTotalTry it locally
Define a Greeter interface with Greeting() string and a Label function returning "user: " plus the greeting. Test with a fixed greeting of "Ada". Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Testing fundamentals 04: Use temporary fixtures and test doubles
Check the lesson objective before moving on.
Why use t.TempDir?
What does a fixed test double establish?