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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
