Using Mox in unit tests
by Paulo Gonzalez
2021-12-16 | elixir mox tests
Edit: Part of this tutorial made it to the Mox project part of this tutorial made it to the Mox project as an example of basic usage. Great stuff!
Let's take a look at setting up Mox to help defining contracts within an Elixir application. Below are simplified `git diff`s from an example application I created to demonstrate Mox from first principles. You can find the link to it below. Each of the diffs is a commit in the repo.
# mix.exs
defp deps do
[
+ {:mox, "~> 1.0", only: :test}
]
end
# lib/weather_behaviour.ex
defmodule WeatherBehaviour do
@callback get_weather(binary()) :: {:ok, map()} | {:error, binary()}
end
# lib/weather_impl.ex
defmodule WeatherImpl do
@moduledoc """
An implementation of a WeatherBehaviour
"""
@behaviour WeatherBehaviour
@impl WeatherBehaviour
def get_weather(city) when is_binary(city) do
# Here you could call an external api directly with an HTTP client or use
# a third party library that does that work for you. In this example we send a
# request using a `httpc` to get back some html, which we can process later.
:inets.start()
:ssl.start()
case :httpc.request(:get, {"https://www.google.com/search?q=weather+#{city}", []}, [], []) do
{:ok, {_, _, html_content}} -> {:ok, %{body: html_content}}
error -> {:error, "Error getting weather: #{inspect(error)}"}
end
end
end
```
# bound.ex, the main context we chose to call this function from
defmodule Bound do
def get_weather(city) do
weather_impl().get_weather(city)
end
defp weather_impl() do
Application.get_env(:bound, :weather, WeatherImpl)
end
end
# in test/test_helper.exs
+Mox.defmock(WeatherBehaviourMock, for: WeatherBehaviour)
+Application.put_env(:bound, :weather, WeatherBehaviourMock)
ExUnit.start()
# test/bound_test.exs
defmodule BoundTest do
use ExUnit.Case
import Mox
setup :verify_on_exit!
describe "get_weather/1" do
test "fetches weather based on a location" do
expect(WeatherBehaviourMock, :get_weather, fn args ->
# here we can assert on the arguments that get passed to the function
assert args == "Chicago"
# here we decide what the mock returns
{:ok, %{body: "Some html with weather data"}}
end)
assert {:ok, _} = Bound.get_weather("Chicago")
end
end
end
And there we go, we have implemented Mox in an Elixir project!
Mox helps setting clear boundaries and contracts not only with third party apis/libraries/resources but also code from other teams or contexts in a large application. It has been extremely useful in my career while working with Elixir. I highly suggest using it above other alternatives.
Usually, we call to third party APIs (or anything that crosses a boundary/contract) to get some data so we can then do something else with it. In this simple example, we added a function to a higher level abstraction to interact with the implementation. It's pretty silly, but it demonstrates how Mox can verify the arguments that are passed to that function and assert that the mock is called in the execution. Let's explore something that would resemble a feature we would see in a production application:
# Example A
defmodule DailyUserEmail do
require Logger
def send_emails(users) do
Logger.info("Started to send daily emails")
result = Enum.reduce(users, %{success_count: 0, error_count: 0}, fn user ->
with {:ok, %{city: city}} <- Accounts.get_user_city(user),
{:ok, weather_details} <- weather_impl().get_weather(city),
{:ok, _} <- email_client_impl().send_email(%{user: user, template: :daily, weather_details: weather_details}) do
Logger.info("Successfully sent daily email to user_id #{user.id}")
%{acc | success_count: acc.success_count + 1}
else
error ->
Logger.error("Unable to send email to user_id #{user.id}, error: #{inspect(error)}")
%{acc | error_count: acc.error_count + 1}
end
end)
Logger.info("Finished sending daily emails, result: #{inspect(result)}")
result
end
defp weather_impl() do
Application.get_env(:bound, :weather, WeatherImpl)
end
defp email_client_impl() do
Application.get_env(:bound, :email, MailGunImpl)
end
end
Both the implementations above could be mocked in our unit tests.
Here is the code for the example app I created, feel free to look at the commits. Here is the Mox documentation and a Mox lesson in Elixir School.
Thanks for reading!