Testing in Laravel
SlidesThis 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.
Why Write Tests?
Section titled “Why Write Tests?”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.
Folders and Files
Section titled “Folders and Files”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.
The Test Environment
Section titled “The Test Environment”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.phppest()->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 nullIf 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.
Running tests
Section titled “Running tests”You can run the whole test suite with:
php artisan testFeature Tests
Section titled “Feature Tests”HTTP Tests
Section titled “HTTP Tests”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); });});Sessions
Section titled “Sessions”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'); });});Browser Tests
Section titled “Browser Tests”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.
Manipulating Time
Section titled “Manipulating Time”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).Factory
Section titled “Factory”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:
$ 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....Using a Factory
Section titled “Using a Factory”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]);});Implementing a Factory
Section titled “Implementing a Factory”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().
Example: the User Factory
Section titled “Example: the User Factory”Laravel already comes with a factory for users.
We only add the column status, which our app needs:
// file database/factories/UserFactory.phpclass 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 theemailcolumn 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 ispassword. - The default status is
STUD, because most users are students.
Example: a different type of User
Section titled “Example: a different type of User”// file database/factories/UserFactory.phpclass 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.
Example: the Event Factory
Section titled “Example: the Event Factory”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.phpuse 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']).
Keep Factories up-to-date
Section titled “Keep Factories up-to-date”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.locationTo create several records at once, use count():
$events = Event::factory()->count(3)->create();Relationships and Factories
Section titled “Relationships and Factories”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);});Final Quiz
Section titled “Final Quiz”Which test belongs in tests/Feature?
- A test for a plain PHP class that formats prices
- A test that requests
/eventsand 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 -
RefreshDatabasegives 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=STAFFinphpunit.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:freshbefore 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 - withoutcopy(), 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
locationto$fillablein the Event model - Pass a
locationin every test that creates an event - Add
locationto thedefinition()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
Answered: 0 / 0 (0%)
Correct: 0 / 0 (0%)