intermediate
Step 10 of 15
Testing in Laravel
Laravel Framework
Testing in Laravel
Laravel is built with testing in mind, providing a rich set of testing utilities out of the box. Feature tests make HTTP requests to your application and assert responses, simulating real user interactions. Unit tests verify individual classes and methods in isolation. Laravel's testing helpers make it easy to interact with the database, authenticate users, mock services, and assert JSON responses. A well-tested application gives you confidence to refactor and add features without breaking existing functionality.
Feature Tests
<?php
namespace Tests\Feature;
use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class PostTest extends TestCase
{
use RefreshDatabase;
public function test_user_can_view_posts_list(): void
{
Post::factory(5)->create();
$response = $this->get('/posts');
$response->assertStatus(200);
$response->assertViewHas('posts');
}
public function test_authenticated_user_can_create_post(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)->post('/posts', [
'title' => 'Test Post',
'body' => 'Test body content',
'category' => 'tech',
]);
$response->assertRedirect();
$this->assertDatabaseHas('posts', [
'title' => 'Test Post',
'user_id' => $user->id,
]);
}
public function test_guest_cannot_create_post(): void
{
$response = $this->post('/posts', ['title' => 'Test']);
$response->assertRedirect('/login');
}
public function test_api_returns_paginated_posts(): void
{
$user = User::factory()->create();
Post::factory(25)->for($user)->create();
$response = $this->actingAs($user, 'sanctum')
->getJson('/api/posts');
$response->assertOk()
->assertJsonStructure([
'data' => [['id', 'title', 'category']],
'meta' => ['current_page', 'total'],
]);
}
}
// Run tests: php artisan test
// Run specific: php artisan test --filter=test_user_can_create_post
Pro tip: UseRefreshDatabasetrait to reset the database between tests and factories to create test data. TheactingAs()method authenticates a user for the test request. UseassertDatabaseHas()to verify data was actually stored in the database.
Key Takeaways
- Feature tests simulate HTTP requests; unit tests verify individual components.
- Use
RefreshDatabasetrait and factories for clean, reproducible test data. actingAs()authenticates test requests;assertDatabaseHas()verifies database state.- Test both success paths and error/unauthorized paths for complete coverage.
- Run tests with
php artisan test— Laravel uses PHPUnit under the hood.