Testing the Actual Interaction with Services

Testing Elixir — by Andrea Leopardi, Jeffrey Matthias (27 / 80)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 The Hidden Benefits of Dependency Doubles | TOC | End-to-End Tests 👉

When working with third-party APIs like the weather API, we push the code that integrates with the API to the outside of our application in a lightweight wrapper. When we’re testing our application, we’re able to swap out that small part with a double to run the rest of our application. At some point, though, we also need to make sure that the code that talks to the API works. In this section, we’ll learn about the different approaches to do that.

In our weather API application, the code that talks to the weather API is this:

integration_tests/soggy_waffle/weather_api.ex

​ ​defmodule​ SoggyWaffle.WeatherAPI ​do​
​ @spec get_forecast(String.t()) ::
​ {​:ok​, map()} | {​:error​, reason :: term()}
​ ​def​ get_forecast(city) ​when​ is_binary(city) ​do​
​ app_id = SoggyWaffle.api_key()
​ query_params = URI.encode_query(%{​"​​q"​ => city, ​"​​APPID"​ => app_id})

​ url =
​ ​"​​https://api.openweathermap.org/data/2.5/forecast?"​ <> query_params

​ ​case​ HTTPoison.get(url) ​do​
​ {​:ok​, %HTTPoison.Response{​status_code:​ 200} = response} ->
​ {​:ok​, Jason.decode!(response.body)}

​ {​:ok​, %HTTPoison.Response{​status_code:​ status_code}} ->
​ {​:error​, {​:status​, status_code}}

​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.