Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

18b - Elixir crash course #21: ExUnit (unit testing)

Learn how to write automated tests using Elixir's built-in ExUnit testing framework

By Daniel Bergholz • Aug 19, 2025

Learn how to write automated tests using Elixir’s built-in ExUnit testing framework.

”Wrong” way of testing

  • Manually run code, inspect results by hand—not repeatable or robust

”Right” way (with ExUnit)

  • Use Elixir’s built-in ExUnit framework to run automated repeatable tests with mix test

Running tests

  • Place tests in the test/ directory
  • Run mix test to execute all tests, or specify a file or line to run just those tests

Test structure & conventions

  • Use defmodule ...Test and use ExUnit.Case
  • Write tests with the test "description" do ... end macro
  • assert for checking expectations; refute for negating them

Test scripts & automation

  • Can configure test scripts in your mix.exs for consistent workflow
  • Tests run in parallel by default for speed (except those that share state or use async: false)

The use macro

  • use ExUnit.Case, async: true sets up the test environment
  • doctest macro lets you write tests in your docs (@doc), and runs them automatically

Writing practical tests

  • Example: Test creating a user with no params returns an error, creating with params works, etc.
  • Can pattern match directly in test setup or test assertions for more descriptive, tight checks

Setup/context & callbacks

  • Use setup and setup_all for test prep, sharing state/context among multiple tests
  • Pattern match on the returned context in individual tests for custom per-test state

Test coverage

  • Run with mix test --cover to see which lines of code are tested

Summary

ExUnit is Elixir’s slick, parallel, and repeatable unit/integration testing tool. It offers clear syntax, per-file and per-test targeting, helpful macros (doctest, assert, setup), and keeps your codebase robust, maintainable, and well-documented.

Related

#phoenix-and-elixir #phoenix-crash-course #daniel-bergholz