TExcelTAD
Home › Elixir › Elixir Testing with ExUnit

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:

elixir
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

A test module test/cart_test.exs:

elixir
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
text
$ mix test
Running ExUnit with seed: 431204, max_cases: 16

....
Finished in 0.02 seconds (0.02s async, 0.00s sync)
4 tests, 0 failures
  • use ExUnit.Case brings in the test macros; async: true lets this module run in parallel with other async modules.
  • describe groups tests; test "name" do ... end defines one.
  • assert expr passes when expr is truthy. assert pattern = expr passes when the pattern matches, and binds its variables for later assertions.
  • refute expr is the opposite of assert. assert_raise ArgumentError, fn -> ... end checks 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:

text
  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: 14

The 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:

elixir · try it yourself
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}")
end
PASS  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:

elixir
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
end

Processes 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:

elixir · try it yourself
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:

elixir
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
end

This 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?

  1. Compares with ==
  2. Passes if the result matches the pattern, and binds user
  3. Always passes
  4. Raises if user is nil

What does async: true in use ExUnit.Case mean?

  1. Tests use Task.async
  2. The module's tests can run concurrently with other async modules
  3. Tests run in the background after mix test exits
  4. Assertions are asynchronous

What does doctest MyModule test?

  1. Spelling in docs
  2. The iex> examples in the module's documentation
  3. That every function has a @doc
  4. The module's typespecs