cheatsheets/exunit.md

107 lines
1.4 KiB
Markdown
Raw Permalink Normal View History

2016-06-18 16:19:06 +00:00
---
title: ExUnit
category: Elixir
2020-07-04 13:33:09 +00:00
updated: 2018-11-19
2016-06-18 16:19:06 +00:00
---
2017-08-24 14:14:46 +00:00
### Test cases
2016-06-18 16:19:06 +00:00
```elixir
defmodule MyTest do
use ExUnit.Case
use ExUnit.Case, async: true # for async
test "the truth" do
assert 1 + 1 == 2
end
end
```
### Capture IO
```elixir
import ExUnit.CaptureIO
test "capture io" do
result = capture_io(fn ->
IO.puts "sup"
end)
assert result == "sup\n"
end
```
### Capture logs
```elixir
config :ex_unit, capture_logs: true
```
### Async
```elixir
defmodule AssertionTest do
# run concurrently with other test cases
use ExUnit.Case, async: true
end
```
2017-08-24 14:14:46 +00:00
### Assertions
2016-06-18 16:19:06 +00:00
```elixir
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"
2017-08-24 14:14:46 +00:00
```
2016-06-18 16:19:06 +00:00
2017-08-24 14:14:46 +00:00
See: [Assertions](http://devdocs.io/elixir/ex_unit/exunit.assertions)
2016-06-18 16:19:06 +00:00
2018-02-12 07:34:00 +00:00
## Setup
### Pattern matching
```elixir
setup do
{:ok, name: "John"}
end
```
```elixir
test "it works", %{name: name} do
assert name == "John"
end
```
### Setup
```elixir
defp my_hook(_context) do
# Invoked in every block in "a block"
{:ok, name: "John", age: 54}
end
2018-02-12 07:34:00 +00:00
describe "a block" do
setup [:my_hook]
test "John's age", context do
assert context[:name] == "John"
assert context[:age] == 54
end
2018-02-12 07:34:00 +00:00
end
```
2016-06-18 16:19:06 +00:00
## Also see
2017-08-24 14:14:46 +00:00
{: .-one-column}
2016-06-18 16:19:06 +00:00
2018-11-20 06:18:50 +00:00
* [ExUnit Docs](http://devdocs.io/elixir/ex_unit/exunit#configure/1)