| 1 |
.. _test-anatomy: |
| 2 |
|
| 3 |
Anatomy of a test |
| 4 |
================= |
| 5 |
|
| 6 |
In the simplest terms, a test is meant to look at the result of a particular |
| 7 |
behavior, and make sure that result aligns with what you would expect. |
| 8 |
Behavior is not something that can be empirically measured, which is why writing |
| 9 |
tests can be challenging. |
| 10 |
|
| 11 |
"Behavior" is the way in which some system **acts in response** to a particular |
| 12 |
situation and/or stimuli. But exactly *how* or *why* something is done is not |
| 13 |
quite as important as *what* was done. |
| 14 |
|
| 15 |
You can think of a test as being broken down into four steps: |
| 16 |
|
| 17 |
1. **Arrange** |
| 18 |
2. **Act** |
| 19 |
3. **Assert** |
| 20 |
4. **Cleanup** |
| 21 |
|
| 22 |
**Arrange** is where we prepare everything for our test. This means pretty |
| 23 |
much everything except for the "**act**". It's lining up the dominoes so that |
| 24 |
the **act** can do its thing in one, state-changing step. This can mean |
| 25 |
preparing objects, starting/killing services, entering records into a database, |
| 26 |
or even things like defining a URL to query, generating some credentials for a |
| 27 |
user that doesn't exist yet, or just waiting for some process to finish. |
| 28 |
|
| 29 |
**Act** is the singular, state-changing action that kicks off the **behavior** |
| 30 |
we want to test. This behavior is what carries out the changing of the state of |
| 31 |
the system under test (SUT), and it's the resulting changed state that we can |
| 32 |
look at to make a judgement about the behavior. This typically takes the form of |
| 33 |
a function/method call. |
| 34 |
|
| 35 |
**Assert** is where we look at that resulting state and check if it looks how |
| 36 |
we'd expect after the dust has settled. It's where we gather evidence to say the |
| 37 |
behavior does or does not align with what we expect. The ``assert`` in our test |
| 38 |
is where we take that measurement/observation and apply our judgement to it. If |
| 39 |
something should be green, we'd say ``assert thing == "green"``. |
| 40 |
|
| 41 |
**Cleanup** is where the test picks up after itself, so other tests aren't being |
| 42 |
accidentally influenced by it. |
| 43 |
|
| 44 |
At its core, the test is ultimately the **act** and **assert** steps, with the |
| 45 |
**arrange** step only providing the context. **Behavior** exists between **act** |
| 46 |
and **assert**. |