What Is a Test Fixture?

A test fixture is the fixed, known state or set of data set up before a test runs, ensuring the test starts from consistent, predictable conditions.

Published November 16, 2026

A test fixture is the fixed state or data set up before a test runs, such as database rows, files or objects, so the test starts from a known, repeatable baseline.

The concept

Fixtures remove hidden dependencies: every test gets the same starting data. Frameworks provide setup and teardown hooks (beforeEach/afterEach) to create and clean them.

Factories and builders generate fixtures programmatically so tests stay readable.

Lifecycle

  1. Set up: create data / start services
  2. Run the test
  3. Assert the outcome
  4. Tear down: clean everything

Practical examples

Jest hooks

let db
beforeEach(async () => { db = await createTestDb(); await db.insert('users', { id: 1, name: 'Ada' }) })
afterEach(async () => { await db.close() })

pytest fixture

import pytest
@pytest.fixture
def user(db):
    return db.create_user(name='Ada')

def test_name(user): assert user.name == 'Ada'

Laravel factory

$user = User::factory()->create(['email' => 'a@x.com']);

Common mistakes

  • Tests that depend on data left by other tests.
  • Huge fixtures where most data is irrelevant.
  • Not cleaning up.

Key takeaways

  • Known starting state for tests.
  • Setup and teardown hooks.
  • Use factories for readability.

FAQ

Fixture vs mock?

A fixture is data/environment; a mock replaces behaviour.

Where do fixtures live?

In test setup code or fixture files near the tests.

More General articles