简体   繁体   中英

More human-friendly tests messages with Erlang EUnit?

I am used to JavaScript testing, especially its BDD frameworks and libraries like Chai where I can describe tests in a human-friendly manner and name tests with strings, eg "UserProfile -> Update First Name", then see these message as the output when running tests.

Is it possible to write Erlang tests in a more natural way, or at least, integrate descriptions in to tests run process, not just have them as comments, but see the name of a test which failed?

Yes. To add descriptions to tests, the tests need to be "test objects" instead of plain tests. For example, change this test:

foo_test() ->
    run_foo(),
    ensure_foo_works().

to this:

foo_test_() ->
    ?_test(
      begin
        run_foo(),
        ensure_foo_works()
      end).

That is, the name of the function should end with _test_ , and the body of the test should be wrapped in a ?_test macro. There are other such "wrapper macros" starting with an underscore; for example, a simple assertion can be rewritten like this:

%% before
check_foo_test() ->
    ?assertEqual(ok, foo()).

%% after
check_foo_test_() ->
    ?_assertEqual(ok, foo()).

Once you have a "test object", you can wrap it in a tuple, where the first element is a string:

foo_test_() ->
    {"Ensure that foo works",
     ?_test(
       begin
         run_foo(),
         ensure_foo_works()
       end)}.

check_foo_test_() ->
    {"Check that foo is ok", ?_assertEqual(ok, foo())}.

Those descriptions will be printed when the test fails. If you run eunit in verbose mode, they will be printed when the test executes as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM