【问题标题】:ExUnit without assert/refute, relying solely on pattern matching?没有断言/反驳的 ExUnit,仅依赖于模式匹配?
【发布时间】:2017-04-12 16:56:13
【问题描述】:

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

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

【问题讨论】:

    标签: testing elixir ex-unit


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

    • 对我来说,在比赛中使用断言的主要缺点是您不会在测试结果中得到左右比较
    • assert {:error, :nope} = MyModule.my_fun 真的在测试什么吗?如果模式匹配,它基本上会断言元组{:error, :nope} 是真实的,不是吗?如果模式不匹配,仍然有MatchError
    • @carp 不,不会有任何MatchErrorassert 专门处理 =。我在刚才的答案中添加了一个示例测试失败输出。
    • @Stuart 是的,如果 LHS 是有效值,我会使用 == 来获得漂亮的彩色差异,但如果它不是有效值,这比只使用 @987654337 更好@在测试中。
    • @Dogbert 非常正确,我想当断言 atom 结果时,== 并不是真正必要的。底线是始终使用断言:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 2010-10-22
    相关资源
    最近更新 更多