devnotes.

Testing Laravel Applications

Laravel ships with first-class testing support out of the box, using either PHPUnit or the increasingly popular Pest syntax, plus a rich set of testing helpers for HTTP requests, databases, and mocking.

php artisan make:test PostTest
php artisan make:test PostUnitTest --unit

Feature test example (Pest):

it('allows an authenticated user to create a post', function () {
    $user = User::factory()->create();

    $response = $this->actingAs($user)->post('/posts', [
        'title' => 'My First Post',
        'body'  => 'This is the content.',
    ]);

    $response->assertRedirect('/posts');
    $this->assertDatabaseHas('posts', ['title' => 'My First Post']);
});

Model factories (defined in database/factories) generate realistic fake data using the Faker library — invaluable for both tests and local seeding:

Post::factory()->count(20)->for($user)->create();

Use RefreshDatabase trait to reset the database between tests, Http::fake() to mock outgoing HTTP calls, and Mail::fake() / Queue::fake() / Event::fake() to assert that mail, jobs, or events were triggered without actually sending or processing them. Run the whole suite with php artisan test or ./vendor/bin/pest.

Testing Laravel Apps with PHPUnit and Pest | DevNotes