Testing Techniques for Go

Testing Techniques for Go

In this talk, Marcus Olsson will walk you through some common and uncommon ways you can test your application. Among the things we'll look at are table tests, mocking dependencies, testing HTTP handlers and more. Chances are you'll learn something new, regardless of your previous experience in Go.


Marcus Olsson

May 15, 2018


  1. 2.
  2. 4.

    Assertions When You want to assert that a condition is

    met. Then Use either t.Error() or t.Fatal() to mark the test as failed.
  3. 5.

    Test helpers When You’re making the same assertion in many

    places.* * Make sure you’re not doing excessive validation Then Extract the assertion into a helper function. t.Helper() introduced in Go 1.9
  4. 6.

    _test package When You want to make sure you’re only

    testing the package API. Then Add _test to the package name in the test file.
  5. 7.

    Table tests When You want to test your function for

    more inputs. Then Extract test cases into a slice and loop over them, testing each input with corresponding output.
  6. 8.

    Subtests When You want to create nested test setups. Then

    Use the t.Run() method that will run independently of other subtests. Available since Go 1.7
  7. 9.

    Extract interface When You want to mock a non-trivial dependency,

    e.g. database connections. Then Extract an interface, create a mock implementation and inject it into your system under test.
  8. 10.

    httptest.NewRecorder When You want to test your HTTP handlers. Then

    Use the httptest.Recorder to intercept the response.
  9. 11.

    httptest.NewServer When You want to mock outgoing HTTP requests. Then

    Use the httptest.Server to return a well-defined response of your own. Maybe even a fixture.
  10. 12.

    Fixtures When You want to validate against difficult-to-set-up test data,

    e.g. binary files. Then Create a testdata directory and load your fixture from file. “Directory and file names that begin with "." or "_" are ignored by the go tool, as are directories named "testdata".” https://golang.org/cmd/go