Database Fixtures and Test Data
You'll learn how to create and manage predictable database state for integration tests using fixtures and seed data.
When integration testing code that interacts with a database, you need your database in a known state before each test runs. Otherwise, tests become unpredictable—passing or failing depending on leftover data from previous runs.
Why Database Fixtures Matter
Think of database fixtures like staging a photo shoot. Before photographing a room, you arrange furniture in specific positions. Similarly, database fixtures place your data in a known starting configuration so tests can make reliable assertions about outcomes.
Creating Test Data
Database fixtures typically involve two approaches:
Seed data – Pre-populated rows inserted before tests run. You might create sample users, products, or orders that multiple tests can reference. This data represents the "baseline" state of your database.
Migrations – Scripts that define your database schema (tables, columns, constraints). Running migrations in your test environment ensures the structure matches production, so tests validate against the real schema.
Managing Fixture State
The key challenge is isolation: each test should start with clean, predictable data. Between tests, you'll need to:
- Reset tables to their seed state
- Clear out data created during the previous test
- Re-apply fixtures without rebuilding the entire database (for speed)
Some teams use transactions: wrap each test in a database transaction, then roll it back after the test completes. This leaves the database unchanged without manual cleanup.
Others prefer truncating tables and re-inserting seed data between tests—slower but more explicit.
Key Takeaway: Database fixtures establish predictable starting state for integration tests by seeding known data and managing schema migrations, ensuring tests run independently and reliably against real database structures.