level20dm
level20dm

Reputation: 176

What is preferred way to add setup and teardown methods in an eunit test fixture?

So I want to add a method that is executed before all other tests, and another that is executed when all tests have finished, for example:

test_setup() -> {whatever}.
test_teardown(_) -> {whatever}.

I know I can "manually" do this by explicitly stating all tests to run in a single test:

fixture_test_() ->
  {
    setup,
    fun test_setup/0,
    fun test_teardown/1,
    [test_something/0]
  }
.

I'm hopeful that there is a better way to active this that allows me write the test methods without explicitly adding them to this list. It seems like there should be better support for this?

Upvotes: 0

Views: 404

Answers (2)

marco.m
marco.m

Reputation: 4849

As Pascal wrote, unfortunately EUnit doesn't have test case autoregistration.

On the other hand, if you write the test functions inline and use "test titles", you can obtain the equivalent of autoregistration:

fixture_test_() ->
    {
        setup,
        fun test_setup/0,
        fun test_teardown/1,
        [
            % Simplest possible. One single assertion.
            % Note the presence of the "_" prefix.
            {"description of test case 1",
             ?_assert(true)
            },
            % Slighly more complicated: multiple assertions inside a list.
            % Note the presence of the "_" prefix.
            {"description of test case 2", [
                ?_assert(true),
                ?_assert(true),
                ?_assert(true)
            ]},
            % Even more complicated, when you really need a function.
            % Note the absence of the "_" prefix.
            {"description of test case 3",
             fun() ->
                 X = f1(),
                 Y = f2(X),
                 ?assertEqual(foo, Y)
             end}
        ]
    }.

When running with verbose mode on:

$ rebar eunit suite=pizza
==> mcs (eunit)
======================== EUnit ========================
module 'pizza'
  module 'pizza_tests'
    pizza_tests:29: fixture_test_ (description of test case 1)...ok
    description of test case 2
      pizza_tests:34: fixture_test_...ok
      pizza_tests:35: fixture_test_...ok
      pizza_tests:36: fixture_test_...ok
      [done in 0.009 s]
    pizza_tests: fixture_test_ (description of test case 3)...ok
    [done in 0.015 s]
  [done in 0.015 s]
=======================================================
  All 5 tests passed.

Upvotes: 0

Pascal
Pascal

Reputation: 14042

The paragraph about fixtures at learnyousomeerlang explains very well all the the things you can do to automate the test with eunit, but as far a I know you will have to list the test assertions somewhere, in flat or nested lists.

There is also a chapter about common test that may be interesting for you.

Upvotes: 1

Related Questions