Golang / GoLang System Architecture and Testing Interview Questions
What are golden file tests in Go and when should you use them?
Golden file tests compare output against a saved reference file. They are ideal for testing complex output (JSON API responses, generated SQL, HTML) where manually writing the expected value in code is tedious and error-prone.
import "github.com/sebdah/goldie/v2" // Golden file test â output compared against testdata/*.golden func TestUserToJSON(t *testing.T) { g := goldie.New(t, goldie.WithFixtureDir("testdata"), goldie.WithUpdateFlag("update"), // flag: -update ) user := User{ ID: 1, Name: "Alice", CreatedAt: time.Date(2024, 1, 15, 0, 0, 0, 0, time.UTC), } data, err := json.MarshalIndent(user, "", " ") if err != nil { t.Fatal(err) } // Compares with testdata/TestUserToJSON.golden g.Assert(t, "TestUserToJSON", data) } // Manual golden file implementation func assertGolden(t *testing.T, name string, got []byte) { t.Helper() path := filepath.Join("testdata", name+".golden") if *update { // go test -run TestUserToJSON -args -update os.MkdirAll("testdata", 0755) os.WriteFile(path, got, 0644) return } want, err := os.ReadFile(path) if err != nil { t.Fatalf("golden file missing: %s (run with -args -update to create)", path) } if !bytes.Equal(got, want) { diff := diffStrings(string(want), string(got)) t.Errorf("golden file mismatch:\n%s", diff) } } var update = flag.Bool("update", false, "update golden files") // Commit testdata/*.golden files to version control // Update when intentional output changes: // go test -run TestUserToJSON -args -update
More Related questions...