Course contentsShow
← Software Engineering
Lesson 542 of 1,93316. Integration TestingFree lesson

Shared vs Per-Test Fixtures

Choosing between reusing fixtures across tests for speed versus creating fresh fixtures for isolation.

Shared vs Per-Test Fixtures

What you'll learn: How to decide whether to reuse test fixtures across multiple tests or create fresh ones for each test.

The Core Trade-off

When writing integration tests, you face a fundamental choice: should you set up your test fixtures (databases, files, services) once and share them across all tests, or create fresh fixtures for each test? This decision pits execution speed against test isolation.

Shared fixtures are set up once before all tests run and torn down once at the end. This is fast—imagine setting up a database connection pool once instead of hundreds of times. However, if one test modifies the fixture state (adds a record, changes a file), it can affect subsequent tests, creating mysterious failures that disappear when you run tests in isolation.

Per-test fixtures are created fresh before each test and torn down after. Every test gets a clean slate—like cooking in a freshly washed kitchen each time. This guarantees test independence and makes failures deterministic, but it's slower. Creating a database schema 500 times takes time.

When to Choose Each

Use per-test fixtures when:

  • Tests modify fixture state
  • Test independence is critical
  • Setup cost is acceptable (milliseconds, not seconds)

Use shared fixtures when:

  • Fixtures are read-only across tests
  • Setup is expensive (creating schemas, loading large datasets)
  • You're confident tests won't interfere with each other

Many teams start with per-test fixtures for safety, then optimize slow suites by identifying read-only scenarios where sharing is safe.

Key Takeaway: Per-test fixtures guarantee isolation but cost time; shared fixtures improve speed but risk test interdependence—choose based on whether your tests modify shared state and how expensive fixture creation is.