LoginSignup
8
3

More than 5 years have passed since last update.

ElixirでTable Driven Testを書く

Last updated at Posted at 2018-11-09

fukuoka.ex代表のpiacereです
今回もご覧いただいて、ありがとうございます:bow:

Go言語では、ポピュラー(?)らしい「Table Driven Test」のコラムをたまたま読み、Elixirでも似たようなこと、サクッとできるよなー、と思い、書いてみました

まずは実装

defmodule Sample do
    def fee_from_age( age ) when age <= 12, do: 1000
    def fee_from_age( _ ), do: 2000
end

ガード節でシンプルに書け、本体は、2行で終わりです

次に普通のテスト

defmodule Sample do
    @doc """
    ## Examples
        iex> if Sample.fee_from_age( 10 ) != 1000, do: "The judgment of fee is wrong"
        nil
        iex> if Sample.fee_from_age( 20 ) != 2000, do: "The judgment of fee is wrong"
        nil
    """
    def fee_from_age( age ) when age <= 12, do: 1000
    def fee_from_age( _ ), do: 2000
end

doctestで、実装と並べて書けるので、アッサリ終わります

Table Driven Testでテストを書き換える

defmodule Sample do
    @doc """
    ## Examples
        iex> [ 
        ...>   %{ "age" => 10, "fee" => 1000 }, 
        ...>   %{ "age" => 20, "fee" => 2000 }, 
        ...> ] |>
        ...> Enum.map( fn %{ "age" => age, "fee" => fee } -> 
        ...>  if Sample.fee_from_age( age ) != fee, do: "The judgment of fee is wrong" end )
        [ nil, nil ]
    """
    def fee_from_age( age ) when age <= 12, do: 1000
    def fee_from_age( _ ), do: 2000
end

Qiitaでの見やすさのため、テストコードを5回、改行していますが、正味は4行で終わります

Enum.mapでの、リスト処理と、パターンマッチによるマップ分解は、実にエレガントです

終わり

Elixirの記述性の高さと、テストをアッサリ書ける魅力、伝わりました?

p.s.「いいね」よろしくお願いします

ページ左上の image.pngimage.png のクリックを、どうぞよろしくお願いします:bow:
ここの数字が増えると、書き手としては「ウケている」という感覚が得られ、連載を更に進化させていくモチベーションになりますので、もっとElixirネタを見たいというあなた、私達と一緒に盛り上げてください!:tada:

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3