【问题标题】:Custom ExUnit assertions and pattern matching自定义 ExUnit 断言和模式匹配
【发布时间】:2017-11-21 22:17:24
【问题描述】:

我正在编写一个灵活的、基于适配器的错误跟踪库,并提供一组自定义测试断言函数以使集成测试更易于使用。

我有类似的东西

  # /lib/test_helpers.ex 

  ...

  @doc """
  Asserts specific exception and metadata was captured

  ## Example

      exception = %ArgumentError{message: "test"}
      exception |> MyApp.ErrorTracker.capture_exception(%{some_argument: 123})
      assert_exception_captured %ArgumentError{message: "test"}, %{some_argument: 123}
  """
  def assert_exception_captured(exception, extra) do
    assert_receive {:exception_captured, ^exception, ^extra}, 100
  end

这会将确切的异常传递给assert_exception_captured,但在尝试对异常结构进行模式匹配时它不起作用。

我希望能够做到这一点

...
assert_exception_captured _any_exception, %{some_argument: _}

如何使用模式匹配进行这项工作?

非常感谢

【问题讨论】:

  • 您的代码对我来说看起来不错。 MyApp.ErrorTracker.capture_exception 是做什么的?
  • 目前它只是使用消息传递send self(), {:exception_captured, exception, extra}来回显参数
  • 这对我有用。你能添加一个对你来说失败的完整测试用例吗?
  • @Dogbert 我添加了一个我希望能够做什么的示例

标签: elixir ex-unit


【解决方案1】:

如果您希望能够传入模式,则需要使用宏。这是您可以使用宏实现它的方式:

defmacro assert_exception_captured(exception, extra) do
  quote do
    assert_receive {:exception_captured, ^unquote(exception), unquote(extra)}, 100
  end
end

测试:

test "greets the world" do
  exception = %ArgumentError{message: "test"}
  send self(), {:exception_captured, exception, %{some_argument: 123}}
  assert_exception_captured exception, %{some_argument: _}
end

输出:

$ mix test
.

Finished in 0.02 seconds
1 test, 0 failures

【讨论】:

  • 嗯,对我来说这会导致错误unbound variable _
  • Ah nvm,我使用的是bind_quoted: [...],但如果我使用unquote,它可以工作。我认为它做了同样的事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 2016-05-14
  • 2018-03-12
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多