مارک پلاس

تکنولوژی نوین اینترنتی

نحوه تست کنترلرها و مدل‌ها لاراول

دسته‌بندی‌ها

نحوه تست کنترلرها و مدل‌ها لاراول

 آموزش تست کنترلرها و مدل‌ها در لاراول


لاراول از PHPUnit برای نوشتن تست‌ها استفاده می‌کنه. ما می‌تونیم تست‌های مختلفی برای کنترلرها و مدل‌ها بسازیم:


🧪 ۱. تست کنترلرها (Feature Test)

▶️ ساخت فایل تست

bash
php artisan make:test PostControllerTest

فایل در مسیر tests/Feature/PostControllerTest.php ایجاد میشه.


✍️ تست لیست پست‌ها

php
public function test_index_returns_posts() { $response = $this->get('/posts'); $response->assertStatus(200); $response->assertSee('لیست پست‌ها'); }

✍️ تست ذخیره‌سازی پست

php
public function test_store_creates_post() { $response = $this->post('/posts', [ 'title' => 'عنوان تستی', 'body' => 'محتوای تستی', ]); $response->assertRedirect('/posts'); $this->assertDatabaseHas('posts', ['title' => 'عنوان تستی']); }

🧪 ۲. تست مدل‌ها (Unit Test)

▶️ ساخت تست مدل

bash
php artisan make:test PostModelTest --unit

فایل در مسیر tests/Unit/PostModelTest.php ساخته میشه.


✍️ تست ارتباطات مدل

مثلاً فرض کن مدل Post یک ارتباط belongsTo با User داره:

php
public function test_post_belongs_to_user() { $user = \App\Models\User::factory()->create(); $post = \App\Models\Post::factory()->create(['user_id' => $user->id]); $this->assertInstanceOf(\App\Models\User::class, $post->user); $this->assertEquals($user->id, $post->user->id); }

✍️ تست ویژگی‌های مدل

php
public function test_post_has_title_and_body() { $post = \App\Models\Post::factory()->create([ 'title' => 'نمونه عنوان', 'body' => 'نمونه محتوا', ]); $this->assertEquals('نمونه عنوان', $post->title); $this->assertEquals('نمونه محتوا', $post->body); }

🧪 اجرای تست‌ها

bash
php artisan test

📦 جمع‌بندی

نوع تستابزارمسیر تست‌ها
کنترلرFeature Testtests/Feature/
مدلUnit Testtests/Unit/


فرض کنیم API برای مدیریت Post داریم، و کاربرها با استفاده از JWT لاگین می‌کنن.


🧩 پیش‌نیاز

bash
composer require tymon/jwt-auth php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" php artisan jwt:secret
  • مدل User باید از JWTSubject پیروی کنه.


✅ ساخت تست Feature

bash
php artisan make:test PostApiJwtTest

✍️ محتوای فایل tests/Feature/PostApiJwtTest.php

php
<?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; use App\Models\User; use App\Models\Post; class PostApiJwtTest extends TestCase { use RefreshDatabase; protected $token; protected function setUp(): void { parent::setUp(); // ساخت کاربر و گرفتن توکن JWT $user = User::factory()->create([ 'email' => 'test@example.com', 'password' => bcrypt('password'), ]); $response = $this->postJson('/api/login', [ 'email' => 'test@example.com', 'password' => 'password', ]); $this->token = $response['access_token']; } public function test_create_post_with_jwt() { $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) ->postJson('/api/posts', [ 'title' => 'پست تستی', 'body' => 'محتوای تستی', ]); $response->assertStatus(201) ->assertJson(['title' => 'پست تستی']); $this->assertDatabaseHas('posts', ['title' => 'پست تستی']); } public function test_read_posts_with_jwt() { Post::factory()->count(2)->create(); $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) ->getJson('/api/posts'); $response->assertStatus(200) ->assertJsonStructure([ '*' => ['id', 'title', 'body'] ]); } public function test_update_post_with_jwt() { $post = Post::factory()->create(); $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) ->putJson("/api/posts/{$post->id}", [ 'title' => 'ویرایش شده', 'body' => 'محتوای جدید', ]); $response->assertStatus(200) ->assertJson(['title' => 'ویرایش شده']); $this->assertDatabaseHas('posts', ['title' => 'ویرایش شده']); } public function test_delete_post_with_jwt() { $post = Post::factory()->create(); $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) ->deleteJson("/api/posts/{$post->id}"); $response->assertStatus(204); $this->assertDatabaseMissing('posts', ['id' => $post->id]); } }

🧪 اجرای تست

bash
php artisan test --filter=PostApiJwtTest

🛡 نکات امنیتی

  • تمام درخواست‌ها با Authorization: Bearer TOKEN ارسال می‌شن.

  • برای routeهای محافظت‌شده از middleware زیر استفاده کن:

php
Route::middleware(['auth:api'])->group(function () { Route::apiResource('posts', PostController::class); });

📦 جمع‌بندی عملیات‌های تست‌شده

عملیاتمسیرمتدتوضیح
ایجاد پست/api/postsPOSTبا توکن JWT
لیست پست‌ها/api/postsGETدریافت JSON
ویرایش پست/api/posts/{id}PUTبا احراز هویت
حذف پست/api/posts/{id}DELETEحذف امن

محتوای مرتبط

پست‌های مرتبط