Lesson 5 of 9 · 21m
Fixtures and Factories That Stay Readable
Build minimal test data close to the scenario, use factories for object graphs, and avoid fixture files that become a second production schema.
Bad test data is quiet sabotage. A test says user fixture, but the fixture contains twelve fields, three roles, a discount coupon, and a legacy status. When it fails, nobody knows which part mattered. Test data should be as small as the behavior under test and as close as possible to the assertion.
Show the values that matter
$invite = Invite::create(email: 'new-hire@company.test', expiresAt: new DateTimeImmutable('2026-01-01T00:00:00Z'));
$clock = new FixedClock(new DateTimeImmutable('2026-01-02T00:00:00Z'));
self::assertSame(InviteResult::Expired, $invite->accept($clock));The date is visible because the date is the point. The email can be arbitrary because it is not. That distinction is the readability trick.
Use builders for objects with boring mandatory fields
Domain objects often require data unrelated to the test. A builder centralizes the noise while letting each test override the meaningful part.
final class UserBuilder
{
private array $roles = ['ROLE_USER'];
private bool $active = true;
public function inactive(): self
{
$clone = clone $this;
$clone->active = false;
return $clone;
}
public function build(): User
{
return new User('user@company.test', $this->roles, $this->active);
}
}Tests then say (new UserBuilder())->inactive()->build() instead of constructing seven parameters the scenario does not care about.
Factories belong near the persistence boundary
Database factories are excellent for integration tests because they can create object graphs with valid foreign keys. The rule is the same: only the scenario-specific attributes belong in the test.
$user = UserFactory::new()->active()->withTeam($team)->create();
InvoiceFactory::new()->forUser($user)->overdueByDays(10)->create();Do not make factories smart enough to hide invalid states. If an overdue invoice requires three entities, encode that path explicitly. Future developers need to see causality.
Beware the shared fixture swamp
Large YAML or SQL fixture sets look convenient until every test depends on user_1 being active, admin, verified, and unsubscribed. Then changing one row breaks forty tests. Shared fixtures are acceptable for reference data that truly never changes: countries, currencies, framework seed data. Business entities should be created per test.
Field notes
- Put unusual values in the test body; put mandatory noise in builders and factories.
- Use realistic-looking data, never production personal data copied into tests.
- FakerPHP is fine for names and text, but random inputs should never decide the behavior under test.
- A factory that silently repairs invalid input will prevent you from testing invalid states.
Was this lesson helpful?