Test Fixtures and Setup
You'll learn how to eliminate repetitive test preparation by centralizing common setup and teardown logic.
The Problem: Repetitive Test Preparation
When writing multiple unit tests, you often need the same starting conditions: a database connection, sample data objects, mock services, or configuration. Writing this initialization code in every test leads to duplication, maintenance headaches, and bloated test files.
What Are Test Fixtures?
A test fixture is the fixed state and resources that exist before your test runs. Think of it like setting up a chess board before each game—you arrange the pieces in their starting positions so the game can begin predictably.
Setup and teardown methods let you define this preparation and cleanup logic once and have it automatically run before and after each test (or once per test suite).
How It Works
Most testing frameworks provide special methods or decorators:
- Setup: Runs before each test, creating fresh fixtures
- Teardown: Runs after each test, cleaning up resources
- Suite-level setup/teardown: Runs once before/after all tests in a group
# Using a testing framework's setup mechanism
def setup():
user = create_user("test@example.com")
database = connect_test_db()
return user, database
def teardown(database):
database.close()
def test_user_login(user):
# user fixture is ready to use
assert user.email == "test@example.com"
Why This Matters
Fixtures keep tests DRY (Don't Repeat Yourself), ensure consistency across tests, and make cleanup automatic—preventing resource leaks or contaminated test environments. You write the setup once, and every test benefits.
Key Takeaway: Test fixtures with setup and teardown methods centralize test preparation, eliminating duplication and ensuring each test starts with a clean, predictable state.