Separating Setup, Action, and Assertion in Tests

A test is easier to review when it establishes useful state, performs one operation, and checks the behavior that operation promises.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Use one setup role per value
  2. Check the effect when promised
  3. Separate a fixture from the action being evaluated
  4. Make setup expose only what the behavior requires

Use one setup role per value

To test a stack pop, create a stack containing A then B, invoke pop once, and expect B. If top order is the goal, two distinct entries distinguish it from a queue. Sequence operations for stacks and queues define the expected result.

Check the effect when promised

If removing B is also part of the contract, inspect that A remains. A test that calls pop again just to inspect state performs another effect. Observable side effects guide which aspect you should assert.[1]

Separate a fixture from the action being evaluated

To test draining a queue, initialize it with two jobs, invoke one dequeue, then check both the returned first job and remaining order. If the assertion itself removes a second job, it introduces another action and makes a failure harder to interpret. See FIFO order.

Setup: queue with A then B
Action: remove one item
Assertions: result is A, remaining sequence contains B
Optional independent case: removal from empty queue

Make setup expose only what the behavior requires

Shared fixtures can save duplication, but test-specific details should remain findable. Name values by their role. A test that checks both the result and the state guards against a function that peeks without removing.

References

  1. Python Software Foundation, unittest: Unit Testing Framework ↩