[erlang-questions] I Hate Unit Testing...

Richard Carlsson richardc@REDACTED
Wed Jan 28 13:45:56 CET 2009

Steve Davis wrote:
> What do you think? :)

Honestly? You'll be adding features until you have yet another
framework. As an alternative, here is a suggestion for the
simplest possible use of eunit for the terminally lazy:

If you have a module foo.erl (and you only want to test its exported
functions), create another module foo_tests.erl (under src/ or test/
or wherever, depending on your build structure; just see to it that
the foo_tests.beam file is available in your Erlang code path).

In foo_tests.erl, write:


my_test() ->
    "4" = hex(4),
    true = (hex(5) =/= "6"),
    true = (hex(3) =:= "3"),
    true = (dehex($3) > 20).

and so on. You just use plain Erlang code and write it so that it
crashes (raises an exception, such as a 'badmatch' caused by '=')
if the test does not succeed. Learning curve: practically flat.
Just name your test functions ..._test(), and the -include_lib()
declaration shown above will do all the rest for you: just compile.

To run the tests, call eunit:test(foo) - it will look for the foo_tests
module as well as any tests in foo itself if you have any. (You can
also say eunit:test(foo_tests) if you want to skip those in foo.)

You'll notice that it becomes easier to spot the test that failed if
you don't put them all in the same test function, so separating them
a bit will help:

first_test() -> ...

second_test() -> ...

third_test() -> ...

etc. Each function can test as much or as little as you like.

>From there on, you can learn more features of eunit as you go.
The first thing you might want to use is the ?assertMatch() and
?assert() macros, so that you can do the same kind of tests as
above, but with much more informative error reports. Just write:

my_test() ->
    ?assertMatch("4", hex(4))   %% match pattern against expression
    ?assert(hex(5) =/= "6"),    %% test for true or false
    ?assert(hex(3) =:= "3"),
    ?assert(dehex($3) > 20).

Try it and you'll see the difference when you trigger an error.
This will get you pretty far, and you can still be as lazy as you want.

Of course, any suggestions that might help make eunit even easier to
use are very welcome,


More information about the erlang-questions mailing list