How to write test cases in exUnit

ExUnit is a unit testing framework for the Elixir programming language. It is the built-in testing library that comes with Elixir, and it provides a comprehensive set of tools and functionalities for writing and running tests in Elixir applications.

To write test cases in ExUnit, you need to follow these steps:

  1. Create a test file: Start by creating a new file with a .exs extension in your Elixir project. For example, my_module_test.exs.

  2. Initialize the ExUnit Framework: Import the ExUnit framework by calling ExUnit.start() at the beginning of your test file. This initializes the ExUnit framework and makes its functions and macros available for use.

ExUnit.start()

3. Define the module that needs to be tested: Let's say you have a module called Math that contains some mathematical functions you want to test. Here's an example:

defmodule Math do
def add(a, b) do
a + b
end
def multiply(a, b) do
a * b
end
end

4. Define the test module: Next, you need to define a separate module that will contain your test cases. It should be named after the module you're testing, with the Test suffix. In this case, the test module should be named MathTest. Include the use ExUnit.Case directive in your test module. It imports the necessary macros and functions for writing test cases. Here's an example:

defmodule MathTest do
use ExUnit.Case
# Test case for the add/2 function
test "add/2 should return the sum of two numbers" do
result = Math.add(2, 3)
assert result == 5
end
# Test case for the multiply/2 function
test "multiply/2 should return the product of two numbers" do
result = Math.multiply(4, 5)
assert result == 20
end
end

5. Run the tests: Use the elixir command followed by the test file name, to run the tests:

elixir my_module_test.exs

Here's an overall combined test file that incorporates the previously described code:

ExUnit.start()
defmodule Math do
def add(a, b) do
a + b
end
def multiply(a, b) do
a * b
end
end
defmodule MathTest do
use ExUnit.Case
# Test case for the add function
test "add should return the sum of two numbers" do
result = Math.add(2, 3)
assert result == 5
end
# Test case for the multiply function
test "multiply should return the product of two numbers" do
result = Math.multiply(4, 5)
assert result == 20
end
end

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved