Laravel
Beginner
1 min read
Feature Testing with PHPUnit in Laravel
Example
<?php
// tests/Feature/PostTest.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_authenticated_user_can_view_post_list(): void
{
$user = User::factory()->create();
Post::factory(5)->published()->for($user)->create();
$response = $this->actingAs($user)->get('/posts');
$response->assertOk()
->assertViewIs('posts.index')
->assertViewHas('posts');
}
public function test_guest_cannot_create_a_post(): void
{
$response = $this->post('/posts', ['title' => 'Test', 'body' => str_repeat('a', 50)]);
$response->assertRedirect('/login');
}
public function test_user_can_create_a_post(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)->post('/posts', [
'title' => 'My First Post',
'slug' => 'my-first-post',
'body' => str_repeat('Hello world ', 10),
'status' => 'published',
'category_id' => 1,
]);
$response->assertRedirect();
$this->assertDatabaseHas('posts', ['slug' => 'my-first-post']);
}
}
Related Resources
Laravel Reference
Complete tag & property list
Laravel How-To Guides
Step-by-step practical guides
Laravel Exercises
Practice what you've learned
More in Laravel