design

Laravel'de API Testing: Postman & PHPUnit ile Kapsamlı Test Rehberi

April 4, 2025


1. API Testinin Önemi 🤔

Neden test yapmalıyız?

  • Regresyon hatalarını önler 🐛
  • API stabilitesini garanti altına alır 🏗️
  • Dökümantasyon görevi görür 📝
  • CI/CD pipeline'ını destekler 🔄


// Basit test örneği
public function test_api_returns_success_response()
{
    $response = $this->get('/api/users');
    $response->assertStatus(200);
}


2. PHPUnit ile Temel API Testleri 🛠️

Test Dosyası Oluşturma

php artisan make:test UserApiTest


HTTP Test Metodları

// GET isteği
$response = $this->get('/api/users/1');

// POST isteği
$response = $this->post('/api/users', [
    'name' => 'Test User',
    'email' => 'test@example.com'
]);

// JSON isteği
$response = $this->json('PUT', '/api/users/1', [
    'name' => 'Updated Name'
]);


3. Assertion'lar ile Doğrulama ✅

Status ve Yapı Kontrolleri

$response->assertStatus(200);
$response->assertJson(['success' => true]);
$response->assertJsonStructure([
    'data' => [
        'id',
        'name',
        'email'
    ]
]);


Header ve Validasyon Kontrolleri

$response->assertHeader('Content-Type', 'application/json');
$response->assertJsonValidationErrors(['email']);
$response->assertUnauthorized();


4. Postman ile Gelişmiş Testler 🚀

**Collection Oluşturma

  1. Environment variables tanımlayın
  2. Pre-request Scripts ile test verisi hazırlayın
  3. Tests sekmesinde assertion'lar yazın
// Postman test örneği
pm.test("Status code is 200", function() {
    pm.response.to.have.status(200);
});

pm.test("Response has user data", function() {
    var jsonData = pm.response.json();
    pm.expect(jsonData.data).to.have.property('email');
});


Otomatik Test Çalıştırma

newman run MyCollection.json --environment MyEnv.json


5. Database Transactions ile Test Verisi Yönetimi 🧹

use Illuminate\Foundation\Testing\DatabaseTransactions;

class UserApiTest extends TestCase
{
    use DatabaseTransactions;

    public function test_user_creation()
    {
        $response = $this->post('/api/users', [
            'name' => 'Test',
            'email' => 'test@example.com'
        ]);
        
        $this->assertDatabaseHas('users', [
            'email' => 'test@example.com'
        ]);
    }
}


6. Authentication Testleri 🔐

Sanctum Token Testi

public function test_authenticated_access()
{
    $user = User::factory()->create();
    $token = $user->createToken('test')->plainTextToken;
    
    $response = $this->withHeaders([
        'Authorization' => 'Bearer ' . $token
    ])->get('/api/profile');
    
    $response->assertOk();
}


7. Performans ve Yük Testleri ⏱️

PHPUnit ile Performans Testi

public function test_api_response_time()
{
    $start = microtime(true);
    $this->get('/api/users');
    $this->assertLessThan(0.5, microtime(true) - $start);
}


Artisan Command ile Yük Testi

php artisan test --filter=ApiLoadTest --repeat=100

Test Türleri Karşılaştırması 📊

Test TürüKapsamAraçlarKarmaşıklıkUnitTekil metodlarPHPUnit⭐FeatureAPI Endpoint'lerPHPUnit/Postman⭐⭐IntegrationSistem bileşenleriPostman/Newman⭐⭐⭐LoadPerformansArtillery/Loader⭐⭐⭐⭐


Sağlam API'ler İçin Test Şart! 🏆

Kapsamlı testlerle:

  • Canlıda hata riskini %90 azaltın 📉
  • Geliştirme hızınızı artırın ⚡
  • Daha güvenilir API'ler sunun 🔒


API testlerinizde hangi araçları kullanıyorsunuz? Yorumlarda paylaşın! 💬
Bir sonraki yazımız: 🚀 [Laravel'de API Security: SQL Injection ve XSS'den Korunma] - API'nizi saldırılardan nasıl korursunuz?

#Laravel #APITesting #PHPUnit #Postman #QualityAssurance 🧪

9 + 1 =