Testing the REST API Server

Powerful Command-Line Applications in Go — by Ricardo Gerardi (86 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Developing a REST API Server | TOC | Completing the REST API Server 👉

In addition to manually checking the server with curl, let’s add some structured tests using Go’s testing package. Go provides the package net/http/httptest with additional types and functions for testing HTTP servers.

One approach for testing HTTP servers is testing each handler function individually by using the type httptest.ResponseRecorder. This type allows the recording of an HTTP response for analysis or tests. This approach is useful if you’re using the DefaultServeMux as the server multiplexer.

Because you implemented your own multiplexer function, newMux, you can use a different approach that allows integrated testing, including the route dispatching. You’ll use the type httptest.Server and instantiate a test server providing the multiplexer function as input. This approach creates a test server with an URL that simulates your server, allowing you to make requests similarly to using curl on the actual server. Then you can analyze and test the responses to ensure the server works as designed.

Since you’re going to create this test server multiple times, add a helper function to the test file to help with that. First, create a new test file server_test.go, edit it, and add the package and import sections. For these tests, we’ll use the following packages…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.