by Gregory Vinčić

When it's tedious to update expected outputs from a test, golden files can help. They represent the truth, thus being golden. You assert some output against the content of a golden file, if they differ the test fails and show what has changed. It should be easy to automatically accept the new output as being correct.

import ( "strings" "testing" "" ) func TestMe(t *testing.T) { got := convert("a", "b") golden.Assert(t, got) } func convert(args ...string) string { return strings.Join(args, ",") }

The first time you run this test it will fail as there are no golden file yet.

$ go test
--- FAIL: TestMe (0.00s)
    example_test.go:12: Got ----
        expected ----

exit status 1

Check the output of your test and if it looks ok, save the golden file with

go test -args -update-golden

It created the golden file testdata/package.TestMe and an entry is added to testdata/golden.files which keeps track of used files. If you eg. rename a test the golden file will be saved under a new name. Keep golden.files under revision control to quickly spot which files are no longer used.

With this package you have some flexibility to select the filename. It's sometimes needed when having subtest.

func TestMultiple(t *testing.T) { t.Run("case 1", func(t *testing.T) { golden.AssertWith(t, convert("a", "b"), "testdata/gold_case_1") }) t.Run("case 2", func(t *testing.T) { golden.AssertWith(t, convert("1", "2", "3"), "testdata/gold_case_2") }) }

This method however does not update testdata/golden.files, you'll have to keep track of them some other way.


go get -u
Good luck with your testing!