Testing the Client without Connecting to the API

Learn how to test the client side without connecting to the API.

Overview

Testing our API client by connecting to the real API is hard because we don’t always have full control over the API or the network. Even testing on our local server can be tricky because each test can impact the next. On a real live API, it’s even harder to ensure the tests are reproducible. We might also be unable to test error conditions such as invalid responses or empty lists.

In addition, it’s not nice to hit someone else’s server to test our code, especially if this is part of an automated test pipeline that runs periodically—for example, when using a continuous integration platform.

To overcome these challenges, we mock the API locally for our tests, simulating the expected responses by using the httptest.Server type.

But this approach isn’t perfect. The challenge here is to ensure that the mock data we use to simulate the API response is up-to-date with the actual API. Otherwise, our tests might work locally, but our application will fail when connecting to the live API.

The recommended approach is to have a balance between those two cases. For this application, we’ll use the mock API to run unit tests locally since these tests run often and we don’t want to hit the live API frequently. We’ll add integration tests to our application to execute some final tests to ensure the application works with the live API before shipping it. The key is running the integration tests sporadically.

Creating the cmd/mock_test.go file

We start by defining the resources to mock the API locally. We create and edit the file cmd/mock_test.go. It’s a good practice to use the suffix _test to name files used only during tests to prevent them from being compiled into the final application binary. We add the package definition and the import list.

For this file, we’ll use these packages:

  • net/http to handle HTTP requests.
  • net/http/httptest to instantiate an HTTP test server.

Get hands-on with 1200+ tech skills courses.