Automated tests check that your app still works after every change, so you catch bugs before your users do.
Types of tests
- Feature tests (
tests/Feature) — send a request to a route and check the response, database, redirects - Unit tests (
tests/Unit) — test one small class or function on its own
Laravel supports PHPUnit and Pest. The examples here use PHPUnit.
Create and run
php artisan make:test PostTest— a feature testphp artisan make:test PriceTest --unit— a unit testphp artisan test— run all tests
Helpful tools
use RefreshDatabase;— a clean database for each test (set the test database inphpunit.xml)- Factories —
User::factory()->create() $this->actingAs($user)— log in as a user$this->get('/posts'),$this->post('/posts', [...])
Common assertions
assertOk(), assertStatus(403), assertRedirect('/login'), assertSee('Hello'), assertSessionHasErrors('title'), assertDatabaseHas('posts', [...]).
Start small: test login, your main forms, and permission rules.
Example
Example — Testing post creation
PHP
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class PostTest extends TestCase
{
use RefreshDatabase;
public function test_guests_are_redirected_to_login(): void
{
$this->get('/posts/create')->assertRedirect('/login');
}
public function test_user_can_create_a_post(): void
{
$user = User::factory()->create();
$this->actingAs($user)
->post('/posts', ['title' => 'My test post', 'body' => 'Hello'])
->assertRedirect('/posts');
$this->assertDatabaseHas('posts', ['title' => 'My test post', 'user_id' => $user->id]);
}
public function test_title_is_required(): void
{
$this->actingAs(User::factory()->create())
->post('/posts', ['title' => '', 'body' => 'Hello'])
->assertSessionHasErrors('title');
}
}
php artisan test runs the three tests and prints PASS for each, e.g. "✓ user can create a post". If someone breaks the validation later, test_title_is_required fails.