This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

ExUnit Cheatsheet

A quick reference guide for Elixir's ExUnit built-in test framework: test cases, assertions, refutations, capture IO, and setup callbacks.

· Published

ExUnit is the built-in test framework for Elixir, providing simple macros for defining test cases, assertions, and setup callbacks.

Test Cases

defmodule MyTest do
  use ExUnit.Case
  use ExUnit.Case, async: true  # for async

  test "the truth" do
    assert 1 + 1 == 2
  end
end

Capturing IO

import ExUnit.CaptureIO

test "capture io" do
  result = capture_io(fn ->
    IO.puts "sup"
  end)

  assert result == "sup\n"
end

Capturing Logs

config :ex_unit, capture_logs: true

Asynchronous Tests

defmodule AssertionTest do
  # Run concurrently with other test cases
  use ExUnit.Case, async: true
end

Assertions

assert x == y
refute x == y

assert_raise ArithmeticError, fn ->
  1 + "test"
end

assert_raise ArithmeticError, "message", fn -> ...
assert_raise ArithmeticError, ~r/message/, fn -> ...

flunk "This should've been an error"

See: ExUnit.Assertions.

Setup Callbacks

Pattern Matching in Setup

setup do
  {:ok, name: "John"}
end

test "it works", %{name: name} do
  assert name == "John"
end

Named Hooks in Describe

defp my_hook(_context) do
  # Invoked in every block in "a block"
  {:ok, name: "John", age: 54}
end

describe "a block" do
  setup [:my_hook]

  test "John's age", context do
    assert context[:name] == "John"
    assert context[:age] == 54
  end
end

References

Related topics