GeistHaus
log in · sign up

Go: Debugging Individual Table Tests

matttproud.com

Suppose one day you receive a bug report about your code (func Encode) and want to build a test to verify the fix or recreate the problem. You might have defined your code’s tests in a table-driven format, similar to below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import ( "testing" "github.com/google/go-cmp/cmp" ) func TestEncode(t *testing.T) { for _, test := range []struct { name string input string output string err error }{ // 33 { ... } rows omitted } { t.Run(test.name, func(t *testing.T) { output, err := Encode(test.input) if got, want := output, test.output; got != want { t.Errorf("Encode(%q) output = %q, want %q", test.input, got, want) } // Assume I own the error contract: // // https://matttproud.com/blog/posts/go-errors-and-api-contracts.html if diff := cmp.Diff(test.err, err); diff != "" { t.Errorf("Encode(%q) err = %q, want %q diff (-want,+got):\n%v", test.err, err, diff) } }) } } To fix this, you realize you need to add another row to the table test definition, bringing the total number of rows to 34. Now suppose you add that 34th row to the test, run the test, but the code or the test doesn’t work the way you expect.

0 pages link to this URL

No pages have linked to this URL yet.