Testing the REST API Server
Learn how to write test cases for the REST API server.
We'll cover the following
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 we’re
using the DefaultServeMux
as the server multiplexer.
Because we implemented our own multiplexer function, newMux()
, we can
use a different approach that allows integrated testing, including the route
dispatching. We’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 our server, allowing us to make requests
similarly to using curl on the actual server. Then we can analyze and test
the responses to ensure the server works as designed.
Creating the new test file server_test.go
Since we’re going to create this test server multiple times, we’ll add a helper function
to the test file to help with that. First, we 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:
io/ioutil
to help read the response body.net/http
to deal with HTTP requests and responses.net/http/httptest
, which provides HTTP testing utilities.strings
to compare strings.testing
, which provides testing utilities.
Get hands-on with 1400+ tech skills courses.