Testing
Laravel, PHPUnit ile entegre gelir ve test yazmayı kolaylaştırır.
Test Türleri
# Unit test
php artisan make:test UserTest --unit
# Feature test
php artisan make:test PostControllerTest
Feature Test
count(3)->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',
'content' => 'Test content',
]);
$response->assertRedirect('/posts');
$this->assertDatabaseHas('posts', [
'title' => 'Test Post',
'user_id' => $user->id,
]);
}
public function test_guest_cannot_create_post(): void
{
$response = $this->post('/posts', [
'title' => 'Test Post',
'content' => 'Test content',
]);
$response->assertRedirect('/login');
}
}
API Test
public function test_api_returns_posts(): void
{
Post::factory()->count(3)->create();
$response = $this->getJson('/api/posts');
$response->assertStatus(200)
->assertJsonCount(3, 'data')
->assertJsonStructure([
'data' => [
'*' => ['id', 'title', 'content']
]
]);
}
public function test_api_requires_authentication(): void
{
$response = $this->postJson('/api/posts', [
'title' => 'Test',
'content' => 'Test',
]);
$response->assertStatus(401);
}
Test Çalıştırma
# Tüm testler
php artisan test
# Belirli test
php artisan test --filter=PostControllerTest
# Paralel çalıştırma
php artisan test --parallel
# Coverage raporu
php artisan test --coverage
Önemli Noktalar
- PHPUnit Laravel ile entegre gelir
- Unit test'ler izole kod parçalarını test eder
- Feature test'ler HTTP endpoint'leri test eder
- RefreshDatabase trait ile temiz veritabanı
- Factory'ler test verisi oluşturur