gpt4 book ai didi

testing - 没有断言/反驳的 ExUnit,仅依赖于模式匹配?

转载 作者:行者123 更新时间:2023-11-28 19:46:45 26 4
gpt4 key购买 nike

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

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 也应该足够了。

最佳答案

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

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

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

失败时,您会收到一条错误消息,这比只在没有断言的情况下进行模式匹配要好,例如

  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)

关于testing - 没有断言/反驳的 ExUnit,仅依赖于模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43364255/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com