...

/

Testing the Client without Connecting to the API

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 ...