Skip to content

Elixir Testing — ExUnit, Doctests, and Mocking

DodaTech Updated 2026-06-29 1 min read

In this tutorial, you will learn about Elixir Testing. We cover key concepts, practical examples, and best practices to help you master this topic.

Testing is deeply integrated into Elixir. ExUnit provides a clean, powerful testing framework, and Elixir's emphasis on pure functions makes tests easy to write.

In this tutorial, you'll learn how to test Elixir code effectively.

ExUnit

# test/calculator_test.exs
defmodule CalculatorTest do
  use ExUnit.Case

  test "adds two numbers" do
    assert Calculator.add(2, 3) == 5
  end

  test "divides correctly" do
    assert Calculator.divide(10, 2) == 5
  end

  test "raises on division by zero" do
    assert_raise ArithmeticError, fn ->
      Calculator.divide(1, 0)
    end
  end
end

# Run: mix test

Doctests

defmodule Calculator do
  @doc """
  Adds two numbers.

  ## Examples

      iex> Calculator.add(2, 3)
      5

      iex> Calculator.add(-1, 1)
      0
  """
  def add(a, b), do: a + b
end

# In test file:
defmodule CalculatorTest do
  use ExUnit.Case
  doctest Calculator
end

Setup

defmodule MyAppTest do
  use ExUnit.Case

  setup do
    # Runs before each test
    {:ok, user: %{name: "Alice", role: "admin"}}
  end

  test "uses setup data", %{user: user} do
    assert user.name == "Alice"
  end
end

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro