Test Web API

Learn how to write unit tests on a web API, how to mock HTTP requests, and how to record HTTP responses.

Go fits well for testing web APIs. Thanks to the http package of the Go standard library, it is very easy to launch a web server and serve incoming requests. Whenever an HTTP request reaches our server, one handler is responsible for replying to it with the requested data. To get the data, each handler may call a database, a third-party system, and so on. However, to unit test our HTTP handlers, we don’t want to spin up an actual HTTP server.

The httptest package

The httptest package of the standard library provides us with everything we need to mock a request for our handlers. The interface that a handler has to implement is the following:

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

The ResponseWriter is an interface that contains all the methods used to construct the HTTP response. Conversely, the ...