没有断言/反驳的ExUnit,完全依赖于模式匹配?

时间:2017-04-12 08:29:20

标签: testing elixir ex-unit

我正在测试函数的返回值。哪两个是首选方式?

test "extra verbose, using assert" do
  {:error, reason} = MyModule.my_fun
  assert reason == :nope
end

test "using pattern matching only" do
  {:error, :nope} = MyModule.my_fun
end

我喜欢第一个,因为我现在不需要测试需要assert语句,并且运行测试时的错误消息更具描述性。 Otoh,MatchError的行号也应该足够了。

1 个答案:

答案 0 :(得分:8)

您可以assert使用=来获取assert和更具描述性的错误消息,并且只需一行代码:

assert {:error, :nope} = MyModule.my_fun

==不同,您可以在LHS上使用任何模式,但在这种情况下,=可以替换为==,因为LHS既是有效模式又是值。

如果失败,您将收到一条错误消息,该消息优于仅使用assert进行模式匹配,例如

  1) test the truth (MTest)
     test/m_test.exs:10
     match (=) failed
     code:  {:error, :nope} = MyModule.my_fun()
     right: {:error, :nop}
     stacktrace:
       test/m_test.exs:11: (test)