Parameterized testing with ExUnit

I write an article Parameterized testing with ExUnit.The key concept is using ExUnit.Case.register_test/4 such as

ExUnit.start()

defmodule ParameterizedTest do
  use ExUnit.Case, async: true

  ExUnit.Case.register_attribute __ENV__, :pair

  for {lhs, rhs} <- [{"one", 1}, {"two", 2}, {"three", 3}] do
    @pair {lhs, rhs}

    test "#{lhs} convert to #{rhs}", context do
      {l, r} = context.registered.pair
      assert l === r
    end
  end

  test "pair should not have any value" do
    assert nil === @pair
  end
end

I do not get why do you need attribute at all. Why not:

for {lhs, rhs} <- [{"one", 1}, {"two", 2}, {"three", 3}] do
  test "#{lhs} convert to #{rhs}" do
    assert unquote(lhs) == unquote(rhs)
  end
end
8 Likes

Because I have never thought it until you mentioned.
It seems the code that you write is more smarter than I write. I use it.
Thanks a lot :joy:

4 Likes

I know this is an old forum, but I’m super new to elixir and I’d like to know why this works.

Thanks in advance.

That’s a metaprogramming feature - unquote fragments, which provide an easy way to generate code dynamically.

Learn more at unquote fragments.

If you are interested in metaprogramming, you can:

(And, welcome :wink:

2 Likes