Course contentsShow
← Software Engineering
Lesson 455 of 1,93313. Unit Testing in DepthFree lesson

Test Fixtures vs Builders

Comparing shared fixtures with per-test builders and understanding when each approach is appropriate.

Test Fixtures vs Builders

You'll learn when to share test setup using fixtures and when to create fresh data per test with builders.

The Two Approaches

Both test fixtures and builders solve the problem of creating test data, but they work differently:

Test fixtures are shared setup objects created once (often in setup methods) and reused across multiple tests. They're like having a standard classroom setup that every lesson uses.

Test data builders create fresh objects for each test, customized as needed. They're like preparing a fresh meal for each diner, tailored to their preferences.

When to Use Fixtures

Use fixtures when:

  • Data is truly immutable and can't affect other tests
  • Setup is expensive (database connections, file loading)
  • All tests need identical, simple objects
  • You want to emphasize that tests share a common context
// Fixture approach
let sharedUser;

beforeEach(() => {
  sharedUser = { id: 1, name: "Alice", role: "user" };
});

test("displays user name", () => {
  expect(formatUserName(sharedUser)).toBe("Alice");
});

When to Use Builders

Use builders when:

  • Tests need customized variations of objects
  • Tests might mutate the objects
  • You want clear, self-contained test setup
  • Object creation is inexpensive
  • Each test tells its own story
// Builder approach
test("admin sees delete button", () => {
  const admin = userBuilder().withRole("admin").build();
  expect(canDelete(admin)).toBe(true);
});

test("regular user cannot delete", () => {
  const user = userBuilder().withRole("user").build();
  expect(canDelete(user)).toBe(false);
});

The Trade-off

Fixtures reduce duplication but can hide important context and create test dependencies. Builders are more verbose but make each test independent and clear.

Key Takeaway: Use fixtures for truly shared, immutable setup; use builders when tests need customization, mutation, or independence—builders usually win for mutable domain objects.