gen_event:start_link().

{enter,into,a,scalable,world}.

Erlang Unit Testing

Here is the implementation of a function absolute/1 which simply computes the absolute value of a number using pattern matching similarly to the Erlang BIF erlang:abs/1:

num.erl
1
2
3
4
5
6
-module(num).
-export([absolute/1]).

absolute(Number) when Number < 0 -> -Number;
absolute(0) -> 0;
absolute(Number) -> Number.

It is very simple to understand: the pattern matching processor scans each clause of absolute/1 in the order they are declared, when a clause match then the pattern matching processor selects it and immediately executes the corresponding path of the function.

Now we want to check if the function absolute/1 works as expected by writing a unit test using the EUnit framework included in the Erlang/OTP distribution :

num_test.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
-module(num_test).
-include_lib("eunit/include/eunit.hrl").
-import(num, [absolute/1]).

%% callable via num_test:test().
absolute_test_() ->
    [?_assert(absolute(-10) == 10),
     ?_assert(absolute(-5) == 5),
     ?_assert(absolute(-1) == 1),
     ?_assert(absolute(-0) == 0),
     ?_assert(absolute(0) == 0),
     ?_assert(absolute(1) == 1),
     ?_assert(absolute(5) == 5),
     ?_assert(absolute(10) == 10)].

Then we invoke num_test:test() in the Erlang runtime system:

$ erl
Erlang R16A (erts-5.10) [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V5.10  (abort with ^G)
1> num_test:test().
  All 8 tests passed.
ok

All tests passed successfully.