はじめに
Elixir 1.18 のリリース候補(RC版)が出ました
パラメータ化テストができるようになったとのことで試してみます
Elixir 1.18.0-rc.0 のインストール
asdf で 1.18.0-rc.0 をインストールしました
asdf install elixir 1.18.0-rc.0
カレントディレクトリー配下で 1.18.0-rc.0 を使うように指定します
asdf local elixir 1.18.0-rc.0
プロジェクトの作成
新しいプロジェクトを作成します
mix new main
Elixir プロジェクトに必要な最低限のディレクトリー構造とファイルが作成されます
ディレクトリー内に移動します
cd main
テスト対象処理の実装
lib/main.ex
を以下のように変更します
defmodule Main do
def hello(n) do
case n do
1 -> n + 1
2 -> 0
3 -> n * 2
_ -> 99
end
end
end
テストの実装
lib/main_test.exs
を以下のように変更します
defmodule MainTest do
use ExUnit.Case,
async: true,
parameterize: [
%{input: 1, output: 2},
%{input: 2, output: 0},
%{input: 3, output: 6},
%{input: 4, output: 99}
]
doctest Main
test "hello", %{input: input, output: output} do
assert Main.hello(input) == output
end
end
parameterize
にパラメータ化した変数のパターンを列挙します
test "hello", %{input: input, output: output} do
のように、テストでパラメータを受けます
テストの実行
テストを実行します
mix test
実行結果
Compiling 1 file (.ex)
Generated main app
Running ExUnit with seed: 166756, max_cases: 16
....
Finished in 0.00 seconds (0.00s async, 0.00s sync)
4 tests, 0 failures
4 つのケースについてテストが実行されています
パラメータを書き換えて、わざとエラーを発生させます
defmodule MainTest do
use ExUnit.Case,
async: true,
parameterize: [
%{input: 1, output: 2},
- %{input: 2, output: 0},
+ %{input: 2, output: 8},
%{input: 3, output: 6},
%{input: 4, output: 99}
]
doctest Main
test "hello", %{input: input, output: output} do
assert Main.hello(input) == output
end
end
実行結果
Running ExUnit with seed: 595271, max_cases: 16
...
1) test hello (MainTest)
Parameters: %{input: 2, output: 8}
test/main_test.exs:13
Assertion with == failed
code: assert Main.hello(input) == output
left: 0
right: 8
stacktrace:
test/main_test.exs:14: (test)
Finished in 0.01 seconds (0.01s async, 0.00s sync)
4 tests, 1 failure
Parameters: %{input: 2, output: 8}
というように、どのパラメータでテストに失敗したか分かるようになっています
まとめ
パラメータ化テストにより、テストケースが効率的に書けそうですね