问题
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, e.g. "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?
回答1:
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.
来源:https://stackoverflow.com/questions/38659475/more-human-friendly-tests-messages-with-erlang-eunit