Cheat Sheet速查表
跳转到主要内容

ExUnit 速查表

本文根据 Devhints / ExUnit 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2018-11-19。

测试用例

defmodule MyTest do
  use ExUnit.Case
  use ExUnit.Case, async: true  # for async

  test "the truth" do
    assert 1 + 1 == 2
  end
end

捕获 IO

import ExUnit.CaptureIO

test "capture io" do
  result = capture_io(fn ->
    IO.puts "sup"
  end)

  assert result == "sup\n"
end

捕获日志

config :ex_unit, capture_logs: true

异步

defmodule AssertionTest do
  # run concurrently with other test cases
  use ExUnit.Case, async: true
end

断言

assert x == y
refute x == y

assert_raise ArithmeticError, fn ->
  1 + "test"
end

assert_raise ArithmeticError, "message", fn -> ...
assert_raise ArithmeticError, ~r/message/, fn -> ...

flunk "This should've been an error"

参见: 断言

设置 (Setup)

模式匹配

setup do
  {:ok, name: "John"}
end
test "it works", %{name: name} do
  assert name == "John"
end

设置 (Setup)

defp my_hook(_context) do
  # Invoked in every block in "a block"
  {:ok, name: "John", age: 54}
end

describe "a block" do
  setup [:my_hook]

  test "John's age", context do
    assert context[:name] == "John"
    assert context[:age] == 54
  end
end

另请参阅