Personally, for each package I have one _test.go file with several test functions in (they must take the form
func TestX(t *testing.T)). Each of these test functions runs through all of my regular functions in the package, passing in acceptable data, extreme data (data on the boundaries of acceptable), and invalid data (passing nil in, etc.).
I then test the return values and use
t.Log() to print useful output. If your code doesn’t behave how it is supposed to, you can use
t.Fail() to cause the test to fail, or
t.Errorf()to log an error message and then fail.
One useful technique to help keep the test files smaller is to have a struct type called
testData or something like that, with a field for:
- An instance of the data you will pass in.
- Each expected return value from various functions.
and a function that sets up and returns a slice of initialised test data.
You then only need to call
td := setupTestData(), and loop through each member, passing in and testing the same fields.
Go has useful tools for testing including the very useful
cover tool. Open terminal or command prompt in the package directory and do
go tool cover -html="cover.out" to see a visual representation of how much of your code is covered by your test.