OSDN Git Service

Regular updates
[twpd/master.git] / exunit.md
1 ---
2 title: ExUnit
3 category: Elixir
4 layout: 2017/sheet
5 updated: 2018-11-19
6 ---
7
8 ### Test cases
9
10 ```elixir
11 defmodule MyTest do
12   use ExUnit.Case
13   use ExUnit.Case, async: true  # for async
14
15   test "the truth" do
16     assert 1 + 1 == 2
17   end
18 end
19 ```
20
21 ### Capture IO
22
23 ```elixir
24 import ExUnit.CaptureIO
25
26 test "capture io" do
27   result = capture_io(fn ->
28     IO.puts "sup"
29   end)
30
31   assert result == "sup\n"
32 end
33 ```
34
35 ### Capture logs
36
37 ```elixir
38 config :ex_unit, capture_logs: true
39 ```
40
41 ### Async
42
43 ```elixir
44 defmodule AssertionTest do
45   # run concurrently with other test cases
46   use ExUnit.Case, async: true
47 end
48 ```
49
50 ### Assertions
51
52 ```elixir
53 assert x == y
54 refute x == y
55
56 assert_raise ArithmeticError, fn ->
57   1 + "test"
58 end
59
60 assert_raise ArithmeticError, "message", fn -> ...
61 assert_raise ArithmeticError, ~r/message/, fn -> ...
62
63 flunk "This should've been an error"
64 ```
65
66 See: [Assertions](http://devdocs.io/elixir/ex_unit/exunit.assertions)
67
68 ## Setup
69
70 ### Pattern matching
71
72 ```elixir
73 setup do
74   {:ok, name: "John"}
75 end
76 ```
77
78 ```elixir
79 test "it works", %{name: name} do
80   assert name == "John"
81 end
82 ```
83
84 ### Setup
85
86
87 ```elixir
88 defp my_hook(_context) do
89   # Invoked in every block in "a block"
90   {:ok, name: "John", age: 54}
91 end
92
93 describe "a block" do
94   setup [:my_hook]
95   
96   test "John's age", context do
97     assert context[:name] == "John"
98     assert context[:age] == 54
99   end
100 end
101 ```
102
103
104 ## Also see
105 {: .-one-column}
106
107 * [ExUnit Docs](http://devdocs.io/elixir/ex_unit/exunit#configure/1)