All

Writing Unit Tests Against HTTP Handlers

Episode 6

We show how to write unit tests against HTTP handlers. Using an example API server that proxies the Github API using Google’s go-github client library, we outline and show examples of two methods for testing.

These two methods are:

  1. Direct testing using net/http/httptest.ResponseRecorder
  2. Integrated testing using github.com/arschles/testsrv

Note that the second method is not strictly unit testing because it tests the router and handler at the same time. This technique is necessary in some cases because some routers encourage or require tight coupling with their handlers. The example code shows such an example with Gorilla Mux, a favorite library of this screencast.

Note also that I wrote the testsrv library. It is a convenience wrapper on top of net/http/httptest.Server and example code shows how to use it. Pull requests and issues are welcome on testsrv.

Check out the example code on GitHub and keep on rockin', Gophers!