hex.pmになかったのと、macroの練習がてら parameterized test の記述をサポートするmacroを書いてみました。
すごく簡単なminimamなmacroです 🙂
こんな感じで test_with_params を接頭辞として使います。
defmodule ExParameterizedTest do
use ExUnit.Case, async: true
use ExUnit.Parameterized
test_with_params "add params",
fn (a, b, expected) ->
assert a + b == expected
end do
[
{1, 2, 3}
]
end
test_with_params "create wordings",
fn (a, b, expected) ->
assert a <> " and " <> b == expected
end do
[
{"dog", "cats", "dog and cats"},
{"hello", "world", "hello and world"}
]
end
test_with_params "fail case",
fn (a, b, expected) ->
refute a + b == expected
end do
[
{1, 2, 2}
]
end
end
内部では、 test をそのまま使っているのと、 line numberをそれぞれのテストケースで使っているので、テスト失敗した時でも何行目のパラメータで失敗したのかわかるようになってます。
1) test add params_line11 (ExParameterizedTest)
test/ex_parameterized_test.exs:5
Assertion with == failed
code: a + b == expected
lhs: 2
rhs: 3
stacktrace:
test/ex_parameterized_test.exs:5
Javaだと、@RunWith(Parameterized.class) や @RunWith(Theories.class) を使って書くやり方が推奨されているやつですね。(過去のBlog)
RubyだとRSpecのモジュールやminitestとかでも実装されていますね。