Testing
Elixir Unit Testing
Unit Testing
Elixir unit testing uses assert macros for function tests.
Introduction to Elixir Unit Testing
Unit testing in Elixir is a critical part of the development process. It allows developers to test individual functions or modules in isolation to ensure they work as expected. Elixir provides the ExUnit framework for writing and running unit tests, which includes a set of macros for assertions, such as assert
, refute
, and more.
Setting Up ExUnit
ExUnit is included by default in Elixir, so there's no need for separate installation. To start using it, you'll need to ensure it's started in your test helper file. Here's how you can set it up:
This command starts the ExUnit framework and is typically found in the test/test_helper.exs
file of your Elixir project.
Writing Your First Test
Let's write a simple unit test for a function that adds two numbers. Suppose you have a module named Math
with a function add/2
:
Now, you'll create a test file to verify this function:
In this test, we use the assert
macro to check that Math.add(1, 2)
returns 3
.
Running Your Tests
To run your tests, simply execute the following command in your terminal:
This command will run all the tests in your project and provide output indicating the success or failure of each test.
Using More Assert Macros
Elixir's ExUnit provides several useful macros for assertions beyond assert
. Here are a few examples:
refute
: Checks that an expression evaluates tofalse
.assert_raise
: Verifies that a specific exception is raised.assert_receive
: Waits for a message to be received in a test process.
Here's a sample test using assert_raise
:
In this example, assert_raise
is used to confirm that dividing by zero raises an ArithmeticError
.
Testing
- Testing
- Unit Testing
- Integration Testing
- Mocking
- Property Testing
- Previous
- Testing
- Next
- Integration Testing