Elixir:
Writing tests
How to:
Elixir uses ExUnit as its built-in test framework, which is extremely powerful and easy to use. Here’s a basic example:
- Create a new test file in the
testdirectory of your Elixir project. For example, if you are testing a module namedMathOperations, your test file could betest/math_operations_test.exs.
# test/math_operations_test.exs
defmodule MathOperationsTest do
use ExUnit.Case
# This is a simple test case to check the addition function
test "the addition of two numbers" do
assert MathOperations.add(1, 2) == 3
end
endTo run your tests, use the mix test command in your terminal. If the MathOperations.add/2 function correctly adds two numbers, you’ll see output similar to:
..
Finished in 0.03 seconds
1 test, 0 failuresFor tests involving external services or APIs, you might want to use mock libraries, such as mox, to avoid hitting actual services:
- Add
moxto your dependencies inmix.exs:
defp deps do
[
{:mox, "~> 1.0.0", only: :test},
# other deps...
]
end- Define a mock module in your test helper (
test/test_helper.exs):
Mox.defmock(HTTPClientMock, for: HTTPClientBehaviour)- Use the mock in your test case:
# test/some_api_client_test.exs
defmodule SomeAPIClientTest do
use ExUnit.Case
import Mox
# This tells Mox to verify this mock was called as expected
setup :verify_on_exit!
test "gets data from the API" do
# Setup the mock response
expect(HTTPClientMock, :get, fn _url -> {:ok, "Mocked response"} end)
assert SomeAPIClient.get_data() == "Mocked response"
end
endWhen running mix test, this setup allows you to isolate your unit tests from real external dependencies, focusing on the behavior of your own code. This pattern ensures your tests run quickly and remain reliable, regardless of external service status or internet connectivity.