Elixir Testing with ExUnit
ExUnit is Elixir's built-in test framework. Every Mix project comes with it set up: tests live in test/, files end in _test.exs, and mix test runs them. Tests in Elixir are fast and run concurrently by default, thanks to processes.
Note: A real test run prints timings and a random seed that change on every run, so on this site the tests are shown in non-run blocks with a typical output. The runnable examples show the techniques the tests use.
A first test
Say lib/cart.ex contains:
defmodule Cart do
def total(items), do: Enum.reduce(items, 0, fn %{price: p, qty: q}, acc -> acc + p * q end)
def add(items, item) when item.qty > 0, do: {:ok, [item | items]}
def add(_items, _item), do: {:error, :invalid_quantity}
endA test module test/cart_test.exs:
defmodule CartTest do
use ExUnit.Case, async: true
describe "total/1" do
test "is 0 for an empty cart" do
assert Cart.total([]) == 0
end
test "multiplies price by quantity" do
items = [%{price: 5, qty: 2}, %{price: 3, qty: 1}]
assert Cart.total(items) == 13
end
end
describe "add/2" do
test "rejects a zero quantity" do
assert {:error, :invalid_quantity} = Cart.add([], %{price: 5, qty: 0})
end
test "returns the new list" do
assert {:ok, [item]} = Cart.add([], %{price: 5, qty: 1})
assert item.price == 5
end
end
end$ mix test
Running ExUnit with seed: 431204, max_cases: 16
....
Finished in 0.02 seconds (0.02s async, 0.00s sync)
4 tests, 0 failuresuse ExUnit.Casebrings in the test macros;async: truelets this module run in parallel with other async modules.describegroups tests;test "name" do ... enddefines one.assert exprpasses whenexpris truthy.assert pattern = exprpasses when the pattern matches, and binds its variables for later assertions.refute expris the opposite ofassert.assert_raise ArgumentError, fn -> ... endchecks for exceptions.
Great failure messages
Because assert is a macro, it sees the code, not just the boolean. A failing assert Cart.total(items) == 14 reports both sides:
1) test total/1 multiplies price by quantity (CartTest)
test/cart_test.exs:9
Assertion with == failed
code: assert Cart.total(items) == 14
left: 13
right: 14The code under test
A good habit is to make functions small and pure so they are easy to test. The Cart functions above can be checked directly in a script with plain pattern matching. match?/2 returns a boolean instead of raising, which is handy for quick checks like these:
defmodule Cart do
def total(items), do: Enum.reduce(items, 0, fn %{price: p, qty: q}, acc -> acc + p * q end)
def add(items, item) when item.qty > 0, do: {:ok, [item | items]}
def add(_items, _item), do: {:error, :invalid_quantity}
end
checks = [
{"empty cart totals 0", Cart.total([]) == 0},
{"price x qty", Cart.total([%{price: 5, qty: 2}, %{price: 3, qty: 1}]) == 13},
{"zero qty rejected", match?({:error, :invalid_quantity}, Cart.add([], %{price: 5, qty: 0}))},
{"add returns ok", match?({:ok, [%{price: 5}]}, Cart.add([], %{price: 5, qty: 1}))}
]
for {name, passed} <- checks do
IO.puts("#{if passed, do: "PASS", else: "FAIL"} #{name}")
endPASS empty cart totals 0
PASS price x qty
PASS zero qty rejected
PASS add returns ok
Setup and context
setup runs before each test and can return data that tests receive as their context:
defmodule InventoryTest do
use ExUnit.Case, async: true
setup do
{:ok, pid} = Agent.start_link(fn -> %{"pens" => 3} end)
%{inventory: pid}
end
test "reads stock", %{inventory: inv} do
assert Agent.get(inv, & &1["pens"]) == 3
end
endProcesses started with start_supervised!/1 instead of start_link are stopped automatically after each test.
Testing output: CaptureIO
ExUnit.CaptureIO.capture_io/1 runs a function and returns everything it printed, so you can assert on console output. It works outside tests too:
defmodule Banner do
def show(name) do
IO.puts(String.duplicate("=", String.length(name) + 4))
IO.puts("| #{name} |")
end
end
printed = ExUnit.CaptureIO.capture_io(fn -> Banner.show("Elixir") end)
IO.inspect(printed)
IO.inspect(printed =~ "| Elixir |")
IO.inspect(String.split(printed, "\n", trim: true) |> length())"==========\n| Elixir |\n"
true
2
In a test you would write assert capture_io(fn -> Banner.show("Elixir") end) =~ "| Elixir |" after import ExUnit.CaptureIO. There is also ExUnit.CaptureLog for log messages.
Doctests
Examples in @doc that start with iex> can be run as tests with one line:
defmodule Slug do
@doc """
Builds a URL slug.
iex> Slug.from("Hello World")
"hello-world"
"""
def from(text), do: text |> String.downcase() |> String.replace(" ", "-")
end
defmodule SlugTest do
use ExUnit.Case, async: true
doctest Slug
endThis keeps the documentation honest: if the example stops working, the test suite fails.
Useful commands and tags
| Command | Runs |
|---|---|
mix test |
everything |
mix test test/cart_test.exs:9 |
the test at line 9 |
mix test --failed |
only the tests that failed last time |
mix test --only slow |
tests tagged @tag :slow |
mix test --cover |
with a coverage report |
mix test --seed 0 |
in a fixed order (to reproduce order-dependent failures) |
Test yourself
What does assert {:ok, user} = create_user(params) do?
- Compares with ==
- Passes if the result matches the pattern, and binds
user - Always passes
- Raises if user is nil
What does async: true in use ExUnit.Case mean?
- Tests use Task.async
- The module's tests can run concurrently with other async modules
- Tests run in the background after mix test exits
- Assertions are asynchronous
What does doctest MyModule test?
- Spelling in docs
- The
iex>examples in the module's documentation - That every function has a @doc
- The module's typespecs