Test Setup and Teardown
You'll learn how to use setup and teardown methods to ensure every test starts fresh and cleans up after itself.
The Core Idea
When tests share resources or state, they can interfere with each other—one test's leftovers can cause another to fail unexpectedly. Setup and teardown methods solve this by running automatically before and after each test, creating a clean environment every time.
Think of it like resetting a board game: before each round, you put all the pieces back to their starting positions (setup), play the game (test), then clear everything away (teardown). Without this reset, the next player inherits the previous game's chaos.
How It Works
Setup methods run before each test to:
- Create fresh test data
- Initialize objects in a known state
- Establish database connections or file handles
- Configure test doubles
Teardown methods run after each test to:
- Close connections and file handles
- Delete temporary files or test records
- Release resources
- Reset global state
Most testing frameworks provide hooks like setUp()/tearDown(), beforeEach()/afterEach(), or similar. These ensure isolation—each test gets its own clean slate, regardless of execution order.
Why This Matters
Without proper setup and teardown, you'll encounter "flaky tests" that pass or fail unpredictably based on which tests ran before them. This destroys confidence in your test suite. By religiously cleaning up before and after, you guarantee test independence—tests can run in any order, in parallel, or individually, and always behave the same way.
Key Takeaway: Use setup methods to build a fresh, known starting state for each test, and teardown methods to clean up resources—ensuring every test runs in complete isolation from all others.