Testing with EUnit

EUnit is the test framework that ships with OTP. Erlang code is easy to test because a function is a value with no hidden state: a test calls it with arguments and compares the result. This lesson writes a module, a test module next to it, and reads the report. The rebar3 lesson showed rebar3 eunit over a project; here the test module is run directly, so the lesson needs no project.

A test that runs

The module under test is ordinary code. Its test module lives next to it in a real project (in test, not src) and its name ends in _tests. A zero-arity function whose name ends in _test is a test: EUnit calls it, and a raised exception is a failure. The tests compare with a plain match, so no assertion macro is needed:

stats.erl

-module(stats). -export([sum/1, mean/1]). sum(List) -> lists:sum(List). mean([]) -> 0; mean(List) -> sum(List) / length(List).

stats_tests.erl

-module(stats_tests). -export([sum_test/0, mean_test/0, empty_mean_test/0, sum_check/0]). sum_test() -> 6 = stats:sum([1, 2, 3]). mean_test() -> 2.0 = stats:mean([1, 2, 3]). empty_mean_test() -> 0 = stats:mean([]). sum_check() -> 7 = stats:sum([1, 2, 3]).

erlc stats.erl stats_tests.erl

erl -noshell -pa . -eval 'eunit:test(stats_tests, []), halt().'

All 3 tests passed.

The quiet report is one line, and it is the line a test job checks. With [verbose] EUnit prints a header, one line per test with ok and its time, and a closing count. A failed match raises badmatch, EUnit catches the exception and the verbose report names the test, the value on the left and the value the right side actually returned.

_test and _test_

The trailing underscore changes what a function is. name_test/0 is a simple test: it passes when it returns, and fails when it raises. A name_test_/0 function is a generator: it returns a test set, a description such as {"the empty list", fun() -> 0 = stats:mean([]) end}, and EUnit runs what it describes. The generator form is how a test shares a setup value between several checks.

The macros of the framework live in eunit/include/eunit.hrl, and the Alpine OTP package of this course does not ship that include folder. The tests here therefore compare with = and =:=, which raise exactly the exception a failed assertion raises. On a full OTP install the same test is one line with ?assertEqual.

Assertions without the header

A match is the assertion of the language: 6 = stats:sum([1, 2, 3]) succeeds when the result is 6 and raises badmatch otherwise. A boolean check is true = (Result > 0), and a type check is true = is_float(stats:mean([1, 2])). A wrong match raises badmatch and names the value it met, which is the same information an assertion macro prints. A test that wants a message of its own raises it, and EUnit shows the term: error({expected_positive, -1}).

Read the report

The header line names the run, each test prints its module, its name and ok, and the closing line counts. A failure replaces ok with *failed* and adds the error term and the source position. The report also prints a time per test and one for the run; those change on every run, which is why a test of a course page never compares them.

The test that never ran

The fourth function of stats_tests is called sum_check/0, and the report above counts three tests, not four. Its body matches 7 against a sum of 6, so it would fail at once if EUnit ever called it. The name ends in _check instead of _test, so EUnit does not know it is a test. The suite is green and a deliberately broken check sits in the file.

This is the most common EUnit mistake, and a green run does not rule it out. A project that cares counts its tests or fails when the count is below a number; the xref and static checks lesson shows the job that runs the suite on every change. The Common Test lesson covers the other framework, which a large system uses for integration tests.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which name makes a zero-arity function a simple EUnit test?

    Answer

    sum_test

    EUnit treats functions whose name ends in _test as tests.

  2. What does a function whose name ends in _test_ return?

    Answer

    A test set or generator

    The trailing underscore form is a generator: it builds a test set, often with fixtures.

  3. What makes an EUnit test fail?

    Answer

    A raised exception, such as a failed match

    EUnit lets the function run and counts any exception as a failure; a plain match raises on a wrong value.

  4. Where does a test module usually live in a rebar3 project?

    Answer

    test

    Rebar3 keeps test sources in test, apart from the application code in src.

  5. What does this module print? -module(q1). -export([main/0, sum_test/0, sum_check/0]). sum_test() -> 6 = 3 + 3. sum_check() -> 7 = lists:sum([1, 2, 3]). main() -> Tests = [Name || {Name, 0} <- ?MODULE:module_info(exports), lists:suffix("_test", atom_to_list(Name))], io:format("~p~n", [Tests]).

    Answer

    [sum_test]

    The filter keeps the exported zero-arity names that end in _test; sum_check does not.

  6. What does this module print? -module(q2). -export([main/0, sum_test/0]). sum_test() -> 7 = lists:sum([1, 2, 3]). main() -> Result = try sum_test() of Value -> {passed, Value} catch error:{badmatch, Value} -> {failed, Value} end, io:format("~p~n", [Result]).

    Answer

    {failed,6}

    The match against 7 fails and binds the right-hand value 6, which the catch returns as {failed, 6}.

  7. What does this module print? -module(q3). -export([main/0]). main() -> io:format("~p~n", [is_float(1 / 2)]).

    Answer

    true

    The division of two integers with / returns a float, and is_float/1 confirms it.

  8. What does this module print? -module(q4). -export([main/0]). check() -> true = (3 > 2), ok. main() -> io:format("~p~n", [check()]).

    Answer

    ok

    The match succeeds and check/0 returns ok; a test would pass on this function.

  9. Why does the course not use -include_lib("eunit/include/eunit.hrl")?

    Answer

    The Alpine OTP package has no include folder for it

    The header is absent in this image, so the tests use plain matches instead of the macros.

  10. What does rebar3 eunit do?

    Answer

    Compiles and runs the tests

    The task compiles test modules, runs every _test and _test_ function and prints a summary.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) and rebar3 3.27.3 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev

Изображение баннера