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

car*_*arp 6 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
Run Code Online (Sandbox Code Playgroud)

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

Dog*_*ert 10

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

assert {:error, :nope} = MyModule.my_fun
Run Code Online (Sandbox Code Playgroud)

与之不同的是==,您可以在LHS上使用任何模式,尽管在这种情况下,=可以替换==为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)
Run Code Online (Sandbox Code Playgroud)

  • @carp 不,不会有任何“MatchError”。`assert` 专门处理 `=`。我刚才在答案中添加了一个示例测试失败输出。 (2认同)