In practice-go we often use table driven testing to be able to test all function scenarios. For example the
FindAnagrams() function returns us a list of anagrams found in the dictionary for given input. To be able to test this function properly we need to test multiple cases, like empty input, valid input, invalid input, etc. We could right different asserts to make it, but it’s much more easier to use table tests.
Imagine we have this function:
Here is how our table may look like:
Usually table is a slice of anonymous structs, however you may define struct first or use an existing one. Also we have a
name property describing the particular test case.
After we have a table we can simply iterate over it and do an assertion:
You may use another function instead of
t.Errorf() just logs the error and test continues.
The testify package is very popular Go assertion package to make unit tests clear, for example:
t.Run() will launch a subtest, and if you run tests in verbose mode (
go test -v) you will see each subtest result:
Since Go 1.7 testing package enables to be able to parallelize the subtests by using
(*testing.T).Parallel(). Please make sure that it makes sense to parallelize your tests!
That’s it, enjoy writing table driven tests in Go!