-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanatomy-of-a-test.qmd
89 lines (61 loc) · 2.02 KB
/
anatomy-of-a-test.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
---
title: "Anatomy of a test"
format: html
filters:
- line-highlight
---
A good test makes it clear what it's checking.
When a test mixes setup, running the system, and checking results, it gets confusing. Separating these steps into clear phases helps make the test’s purpose obvious. This way, anyone reading the test can follow along easily.
We can make this separation explicit with Arrange, Act, Assert comments.
Those comments aren't just for show. They help you structure your tests and keep them focused. They also make it easier to spot missing steps or unnecessary complexity. They keep your tests consistent, which makes them easier to read and maintain.
If you are starting to write a test, put those comments in place first, then fill in the blanks.
## Arrange
The first part of each test should setup the environment for the tested code.
```r
test_that("...", {
# Arrange #<<
machine <- deep_thought$connect() #<<
question <- "What is the answer to life, the universe, and everything?" #<<
# Act
# Assert
})
```
## Act
The second part of each test is to call the code that's being tested.
```r
test_that("...", {
# Arrange
machine <- deep_thought$connect()
question <- "What is the answer to life, the universe, and everything?"
# Act #<<
result <- ask_question(machine, question) #<<
# Assert
})
```
## Assert
The third part of each test is to assert that the code behaves as expected.
```r
test_that("...", {
# Arrange
machine <- deep_thought$connect()
question <- "What is the answer to life, the universe, and everything?"
# Act
result <- ask_question(machine, question)
# Assert #<<
expect_equal(result, 42) #<<
})
```
## Teardown if needed
If we need to free resources, we should do that at the end of the test.
```r
test_that(" ", {
# Arrange
machine <- deep_thought$connect()
question <- "What is the answer to life, the universe, and everything?"
# Act
result <- ask_question(machine, question)
# Assert
expect_equal(result, 42)
machine$disconnect() #<<
})
```