Erlang EUnit – introduction

Why do I want to have a battery of EUnit tests?

Show that each part of the module is working as expected (Unit testing)

Be able to see if/how new code breaks existing code (Regression testing)

As part of TDD (Test Driven Development) one should ideally write the tests first, and later write the code that makes the tests go through. This will automatically give you a set of Unit + Regression tests, so that each step in your development cycle is “fastened” in a secure place (a “green light”).

How do I write my first EUnit test?

Now, assuming you have not followed TDD and have an untested list-processing module (module is for demonstration purposes only and serves no other reason)

Thus this module could be tested with the separate test module called mylist_tests(This is good practice since you do not wish to clutter the logic – your real module, with test cases, thus your tests also become portable and regression testing with different versions of code becomes easier).

That was the whole test module, now there are some interesting points with the test module.

The test module name ends with _tests, this is to allow the eunit test function to find the tests for your module by simply referencing the source module (mylist.erl)

The test module does not export any functions explicitly

The test module includes the eunit header file -include_lib(“eunit/include/eunit.hrl”), this is a most important part since this will automatically export all the tests in the module and cause them to be executed once we start.

Test function names end with _test(), this is a requirement for eunit to identify tests

How do I run my eunit tests?

Save the mylists.erl and mylists_tests.erl in the same directory (for this basic guide).

So, what did I do? I removed our previous mess (the beams), created the source directory, the test directory and the ebin directory. Each one of them should contain source modules, test modules and beam files.

Next off, lets compile properly and run the tests, this time standing at the top level