Testing HTTP Requests Locally

Overview

So far, the tests that we’ve added to this application have focused on the response we obtained from the REST API. This is acceptable as the requests were less complex than the responses for the commands list and view.

For the add command, the scenario is reversed. The simple response has a status and no body, but the request has more details, including a JSON payload and additional headers. We want our tests to ensure the application sends a valid request so we’re confident it’s going to work properly.

If we were testing this application by connecting directly to the actual API server, it wouldn’t be an issue since the server would throw an error if the request was invalid. But since we’re testing this locally using a mock HTTP server, the server doesn’t validate the request’s content.

Updating the cmd/mock_test.go file

The mock HTTP server accepts a function as input. Let’s use Go’s functional nature again and the concept of closures to include the required checks in the function we use when instantiating a new test server. We define the todoRouter() function that included the file name to save the list.

Before we do that, we edit the file cmd/mock_test.go to include the simulated response for the add operation into the testResp map:

Get hands-on with 1400+ tech skills courses.