我正在测试函数的返回值。哪两个是首选方式?
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
的行号也应该足够了。
答案 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)