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:
Create a test file: Start by creating a new file with a
.exsextension in your Elixir project. For example,my_module_test.exs.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 dodef add(a, b) doa + benddef multiply(a, b) doa * bendend
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 douse ExUnit.Case# Test case for the add/2 functiontest "add/2 should return the sum of two numbers" doresult = Math.add(2, 3)assert result == 5end# Test case for the multiply/2 functiontest "multiply/2 should return the product of two numbers" doresult = Math.multiply(4, 5)assert result == 20endend
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 dodef add(a, b) doa + benddef multiply(a, b) doa * bendenddefmodule MathTest douse ExUnit.Case# Test case for the add functiontest "add should return the sum of two numbers" doresult = Math.add(2, 3)assert result == 5end# Test case for the multiply functiontest "multiply should return the product of two numbers" doresult = Math.multiply(4, 5)assert result == 20endend
Free Resources