Req API Client Testing

submited by
Style Pass
2024-04-02 15:00:07

In recent discussions with one of our Elixir Development Subscription clients, the topic of HTTP API client testing came up. In this article we’ll walk through an imaginary third party API integration and discuss testing approaches and affordances provided by Req.

Imagine we’re building an app that displays the weather for a given location using a third-party HTTP weather service. We might have code similar to this:

Unfortunately this function is not so easy to test because it performs an external API request on every call. Such network requests can be flaky, slow, expensive, etc. A popular solution is to use mocks and stubs: just stub out a function call or two and move on, right? However, exactly because these network requests can be slow & flaky, they tend to be the source of many, if not most, performance and reliability issues in applications. Making these pain points stand out can be helpful. There are also real issues with mocks and stubs described next.

Because a mock is meant to replace a real entity, such replacement can only be effective if we explicitly define how the real entity should behave. Failing this, you will find yourself in the situation where the mock entity grows more and more complex with time, increasing the coupling between the components being tested, but you likely won’t ever notice it because the contract was never explicit.

Leave a Comment