Skip to content

Testing in Laravel

Slides

This guide gives an introduction to the mechanisms in Laravel for testing your application.

After reading this guide, you will know:

  • Laravel testing terminology.
  • How to write feature tests for your application.

Laravel makes it easy to write tests. A new Laravel app is ready to run both unit tests and feature tests.

If you run your tests after every change in the code, you know that you did not break anything.

Laravel creates a tests directory for you.

You will find a file that all your test cases inherit from:

  • tests/TestCase.php

and several directories:

  • The Unit directory holds tests that focus on one single class, for example on one model. They are called unit tests.
  • The Feature directory holds tests that use the whole stack: from the HTTP request to the database. They are called feature tests.

By default, every Laravel application has three environments: local, testing, and production.

The configuration for the local environment is set in .env, which is never committed to git.

The configuration for testing is stored in phpunit.xml.

The file tests/Pest.php configures which tests start the Laravel framework. In a new Laravel app, only the feature tests do:

// file tests/Pest.php
pest()->extend(Tests\TestCase::class)
->use(Illuminate\Foundation\Testing\RefreshDatabase::class)
->in('Feature');

So the tests in tests/Unit cannot use the database, factories or config() - they are meant for plain PHP classes. A unit test for a model fails with

Error: Call to a member function connection() on null

If you want to write unit tests for your models, add 'Unit' to the list:

->in('Feature', 'Unit');

RefreshDatabase makes sure that every single test starts with an empty database.

You can run the whole test suite with:

php artisan test

For the parts of your web application that work without JavaScript, you can use HTTP tests. The test sends an HTTP request to your app, and then checks the response with assertions like assertStatus(200). See the available assertions for HTTP tests.

describe('application homepage', function () {
it('returns a successful response', function () {
$response = $this->get('/');
$response->assertStatus(200);
});
});

Laravel has built-in support for sessions and login, and you can use them in tests too: actingAs($user) sends the request as if $user were logged in.

describe('event show page access (English)', function () {
it('lets a staff member view the show page', function () {
$staff = User::factory()->create(['status' => 'STAFF']);
$event = Event::factory()->create(['name' => 'The most important event']);
$response = $this->actingAs($staff)
->get(route('events.show', $event));
$response->assertOk();
$response->assertSee('The most important event');
$response->assertSee('I want to attend');
$response->assertSee('edit Event');
});
});

For functionality implemented with JavaScript you need a browser test. Here the test framework starts a headless browser (a browser without a window) with Playwright. Now we can interact with the web application like a real user:

it('pages through the calendar one month at a time', function () {
// Lines missing
Event::factory()->create([
'name' => 'Event on Calendar Page A',
'start' => '2026-11-20 10:00:00',
'end' => '2026-11-20 12:00:00',
]);
Event::factory()->create([
'name' => 'Event on Calendar Page B',
'start' => '2026-12-15 10:00:00',
'end' => '2026-12-15 12:00:00',
]);
$page = visit(route('events.index'));
// Initially only the first month (November) is visible.
// Then try out the arrow buttons
$page->assertSee('November')->assertDontSee('Dezember');
$page->click('.calendar:visible .calendar__nav button:last-child');
$page->assertSee('Dezember')->assertDontSee('November');
$page->click('.calendar:visible .calendar__nav button:first-child');
$page->assertSee('November')->assertDontSee('Dezember');
});

See the available assertions for browser tests.

The test above stops working once November 2026 is in the past: then the events are no longer in the future, and the calendar does not show them. To keep the test working, we set a fixed “today” at the start of the test:

// Freeze "today", so the event dates below are always in the future,
// no matter when the tests run. This also works in browser tests:
// the calendar in the browser is rendered with this date, too.
$this->travelTo('2026-11-01 09:00:00');
// Two upcoming events in different months → the calendar gets two month
// pages (November and December 2026).

A factory creates test data for a model. When you use php artisan make:model with the option -a (for “all”), it also creates the factory:

Terminal window
$ php artisan make:model Event -a
...
INFO Model [app/Models/Event.php] created successfully.
INFO Factory [database/factories/EventFactory.php] created successfully.
INFO Migration [database/migrations/2025_12_24_123836_create_events_table.php] created successfully.
INFO Seeder [database/seeders/EventSeeder.php] created successfully.
INFO Controller [app/Http/Controllers/EventController.php] created successfully.
INFO Policy [app/Policies/EventPolicy.php] created successfully.
...

In a test, the factory creates records in the test database. You only set the fields that matter for this test:

it('can delete event without stamps', function () {
// Other fields will be filled by the factory automatically
$eventWithoutStamps = Event::factory()->create(['name' => 'Empty Event']);
$id = $eventWithoutStamps->id;
$result = $eventWithoutStamps->delete();
expect($result)->toBeTrue();
$this->assertDatabaseMissing('events', ['id' => $id]);
});

A factory is a class in database/factories/. Its method definition() returns an array with one value for each column of the table. The helper fake() generates random, but realistic looking values: names, email addresses, dates, sentences. Every call gives new values, so every record the factory creates is different.

Follow this rule: Model::factory()->create(), without any arguments, must create a valid record. A test then only sets the values it cares about. They override the values from definition().

Laravel already comes with a factory for users. We only add the column status, which our app needs:

// file database/factories/UserFactory.php
class UserFactory extends Factory
{
protected static ?string $password;
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
'status' => 'STUD',
];
}
}

Some details:

  • unique() makes sure that no email address is used twice in the same test, because the email column in the database is unique.
  • Hashing a password is slow on purpose. ??= hashes it only once, and then reuses the hash for all users. The password of every fake user is password.
  • The default status is STUD, because most users are students.
// file database/factories/UserFactory.php
class UserFactory extends Factory
{
....
// a staff member instead of a student
public function staff(): static
{
return $this->state(fn (array $attributes) => [
'status' => 'STAFF',
]);
}
}

The method staff() is a state: a named variation of the default values. These two lines both create a staff member:

$staff = User::factory()->create(['status' => 'STAFF']);
$staff = User::factory()->staff()->create();

The state is easier to read, and if the way we store “staff” ever changes, we only have to change the factory, not every test.

An event has a name, a start and an end. The end must come after the start, so we calculate the start first, and then use it for the end:

// file database/factories/EventFactory.php
use Illuminate\Support\Carbon;
class EventFactory extends Factory
{
public function definition(): array
{
$start = Carbon::instance(fake()->dateTimeBetween('+1 week', '+2 months'));
return [
'name' => fake()->sentence(3),
'start' => $start,
'end' => $start->copy()->addHours(2),
];
}
}
  • dateTimeBetween('+1 week', '+2 months') picks a random date and time in the future, so the event shows up on pages that list upcoming events.
  • Carbon::instance() turns it into a Carbon date, Laravel’s class for dates. copy() is important: without it, addHours(2) would also change $start.
  • sentence(3) creates a short sentence of fake Latin words, like “Commodi occaecati.”. When the name matters for a test, the test sets it: Event::factory()->create(['name' => 'Empty Event']).

If you add a new required column to the events table later, add it to the factory too. Otherwise every Event::factory()->create() fails with an error like

NOT NULL constraint failed: events.location

To create several records at once, use count():

$events = Event::factory()->count(3)->create();

Factories can also work with relationships. With for() you tell the factory which event and which user the new stamp belongs to:

it('cannot delete event with stamps', function () {
$studentUser = User::factory()->create(['status' => 'STUD' ]);
$eventWithStamps = Event::factory()->create(['name' => 'Locked Event']);
Stamp::factory()
->for($eventWithStamps)
->for($studentUser)
->create();
expect(fn () => $eventWithStamps->delete())
->toThrow(QueryException::class);
});

Which test belongs in tests/Feature?

  • A test for a plain PHP class that formats prices
  • A test that requests /events and checks the HTML in the response
  • A test that checks the syntax of composer.json
  • Every test that uses Pest instead of PHPUnit

One test creates three events. How many events does the next test find at its start?

  • None - RefreshDatabase gives every test an empty database
  • Three, because the tests share one database
  • It depends on the order in which the tests run
  • All events from your local development database

Where is the configuration for the testing environment, for example which database the tests use?

  • In .env
  • In phpunit.xml
  • In tests/TestCase.php
  • In config/testing.php

A checkbox hides table rows with JavaScript. Which kind of test can check that the rows disappear?

  • An HTTP test with $this->get('/orders')
  • A unit test for the model
  • A browser test with visit(), which runs a headless browser
  • None - JavaScript can only be tested by hand

The admin page is only for logged-in staff members. How does a feature test request it as a staff member?

  • $this->actingAs($staff)->get('/admin')
  • $this->get('/admin?user=staff')
  • Set status=STAFF in phpunit.xml
  • Log in by hand in the browser before running the tests

A test uses fixed dates in November 2026. Once that month is over, the test fails. What keeps it working?

  • Set the clock of your computer back to November 2026
  • Call $this->travelTo('2026-11-01 09:00:00') at the start of the test
  • Mark the test as skipped after November
  • Run php artisan migrate:fresh before the tests

What does Event::factory()->create(['name' => 'Empty Event']) create?

  • An event called “Empty Event”; all other columns get values from the factory’s definition()
  • An event with a random name; the array is ignored
  • An event called “Empty Event” where all other columns are null
  • Nothing - you have to pass a value for every column

What is staff() in User::factory()->staff()->create()?

  • A second factory class for staff members
  • A relationship between the User and the Staff model
  • A query that finds all staff members in the database
  • A state: a named variation of the factory’s default values

In the EventFactory, why does the end use $start->copy()->addHours(2)?

  • addHours() changes the date object itself - without copy(), the start would move too
  • copy() turns the date into a string, so the database can store it
  • Dates from fake() are read-only and must be copied before changing them
  • copy() makes sure that no two events end at the same time

You added a required column location to the events table. Now many tests fail with NOT NULL constraint failed: events.location. What is the best fix?

  • Add location to $fillable in the Event model
  • Pass a location in every test that creates an event
  • Add location to the definition() of the EventFactory
  • Run php artisan migrate:fresh

What does for() do in Stamp::factory()->for($event)->for($user)->create()?

  • It creates one stamp for every event in the database
  • The new stamp belongs to this existing event and user, so the factory does not create new ones
  • It runs the factory in a loop, once for each argument
  • It only finds stamps that already belong to this event and user