【问题标题】:Use underscore (_) in ExUnit tests在 ExUnit 测试中使用下划线 (_)
【发布时间】:2016-10-18 22:58:16
【问题描述】:

我的 elixir 应用程序中有一个方法,比如说Some.Module.func/1,它返回一个由两个数字组成的元组。我正在用 ExUnit 编写测试,只需要测试元组中的第一个元素,并不真正关心第二个元素。

到目前为止,我已经尝试过这样做:

test "some method" do
    assert Some.Module.func(45) == {54, _}
end

但我只是在运行测试时收到此错误:

Compiled lib/some.ex
Generated some app
** (CompileError) test/some_test.exs:7: unbound variable _
    (stdlib) lists.erl:1353: :lists.mapfoldl/3
    (stdlib) lists.erl:1354: :lists.mapfoldl/3

为什么这不起作用,我如何忽略测试中不需要的结果?

【问题讨论】:

    标签: unit-testing elixir ex-unit


    【解决方案1】:

    在使用== 时,您不能像这样与断言匹配。您可以使用= 执行以下操作:

    test "some method" do
      assert {54, _} = Some.Module.func(45)
    end
    

    请注意,顺序已颠倒,因为 _ 只能出现在 = 运算符的左侧,否则您将收到 CompileError,这就是您所得到的:

    iex(3)> 3 = _
    ** (CompileError) iex:3: unbound variable _
        (elixir) src/elixir_translator.erl:17: :elixir_translator.translate/2
    

    你也可以这样做:

    test "some method" do
      {result, _} = Some.Module.func(45)
      assert result == 54
    end
    

    这可能适用于您想要对结果执行多个断言的情况。

    【讨论】:

      猜你喜欢
      • 2019-11-20
      • 1970-01-01
      • 2017-06-05
      • 2017-04-09
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      相关资源
      最近更新 更多