首頁  >  文章  >  後端開發  >  如何使用 Pest 在 Laravel 中建立測試案例

如何使用 Pest 在 Laravel 中建立測試案例

WBOY
WBOY原創
2024-08-06 07:13:42935瀏覽

How to Create a Test Case in Laravel Using Pest

測試您的 Laravel 應用程式對於確保您的程式碼按預期工作至關重要。 Pest 是一個 PHP 測試框架,設計簡約且使用者友好。在這篇文章中,我們將逐步使用 Pest 在 Laravel 中建立測試案例,重點放在一個測試雇主記錄創建的範例,包括上傳徽標。

先決條件

  • Laravel 應用程式設定
  • 您的 Laravel 應用程式中安裝了害蟲

如果您還沒有安裝 Pest,您可以按照 Pest 官方安裝指南進行安裝。

第 1 步:設定模型和關係

確保您的使用者和雇主模型正確設定並具有必要的關係。

使用者模型 (app/Models/User.php):

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Relations\HasOne;

class User extends Authenticatable
{
    public function employer(): HasOne
    {
        return $this->hasOne(Employer::class);
    }
}

雇主模型 (app/Models/Employer.php):

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Employer extends Model
{
    protected $fillable = ['name', 'email', 'phone', 'address', 'city', 'website', 'user_id', 'logo'];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}

第二步:設立工廠

建立用於產生測試資料的工廠。

使用者工廠(database/factories/UserFactory.php):

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    protected $model = User::class;

    public function definition()
    {
        return [
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => bcrypt('password'), // password
            'remember_token' => Str::random(10),
        ];
    }
}

雇主工廠(資料庫/工廠/EmployerFactory.php):

namespace Database\Factories;

use App\Models\Employer;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Http\UploadedFile;

class EmployerFactory extends Factory
{
    protected $model = Employer::class;

    public function definition()
    {
        return [
            'name' => $this->faker->company,
            'email' => $this->faker->companyEmail,
            'phone' => $this->faker->phoneNumber,
            'address' => $this->faker->address,
            'city' => $this->faker->city,
            'website' => $this->faker->url,
            UploadedFile::fake()->image('logo.png')
        ];
    }
}

第三步:編寫控制器

建立一個控制器方法來處理雇主的創建。

雇主控制器 (app/Http/Controllers/EmployerController.php):

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employer;
use Illuminate\Support\Facades\Storage;

class EmployerController extends Controller
{
    public function __construct()
    {

    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email',
            'phone' => 'required|string',
            'address' => 'nullable|string',
            'city' => 'nullable|string',
            'website' => 'nullable|url',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        if ($request->hasFile('logo')) {
            $path = $request->file('logo')->store('logos', 'public');
            $validated['logo'] = $path;
        }

        $employer = $request->user()->employer()->create($validated);

        return response()->json($employer, 201);
    }
}

第 4 步:建立 Pest 測試

建立測試文件並編寫測試案例來驗證雇主的創建,包括上傳徽標。

建立測試檔案:

php artisan pest:test EmployerControllerTest

寫測試案例(tests/Feature/EmployerControllerTest.php):

<?php

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\Employer;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

uses(RefreshDatabase::class);

it('prevents guests from creating an employer', function () {
    // Define the data to be sent in the POST request
    $data = [
        'name' => 'Test Employer',
        'email' => 'test@employer.com',
        'phone' => '1234567890',
        'address' => '123 Employer St',
        'city' => 'Employer City',
        'website' => 'https://www.employer.com',
    ];

    // Send the POST request to create the employer as a guest (unauthenticated)
    $response = $this->post('/api/employers', $data);

    // Assert that the response status is 401 (Unauthorized)
    $response->assertStatus(401);

    // Optionally, check that the employer was not created
    $this->assertDatabaseMissing('employers', [
        'name' => 'Test Employer',
        'email' => 'test@employer.com',
    ]);
});

it('creates a new employer for authenticated user', function () {
    // Create a user and log them in
    $user = User::factory()->create();
    Auth::login($user);

    // Define the data to be sent in the POST request
    $data = [
        'name' => 'Test Employer',
        'email' => 'test@employer.com',
        'phone' => '1234567890',
        'address' => '123 Employer St',
        'city' => 'Employer City',
        'website' => 'https://www.employer.com',
    ];

    // Send the POST request to create the employer
    $response = $this->post('/api/employers', $data);

    // Assert that the response status is 201 (Created)
    $response->assertStatus(201);

    // Assert that the employer was created
    $this->assertDatabaseHas('employers', [
        'name' => 'Test Employer',
        'email' => 'test@employer.com',
    ]);
});

it('creates a new employer with a logo', function () {
    // Create a user and log them in
    $user = User::factory()->create();
    Auth::login($user);

    // Fake a storage disk for testing
    Storage::fake('public');

    // Define the data to be sent in the POST request
    $data = [
        'name' => 'Test Employer',
        'email' => 'test@employer.com',
        'phone' => '1234567890',
        'address' => '123 Employer St',
        'city' => 'Employer City',
        'website' => 'https://www.employer.com',
        'logo' => UploadedFile::fake()->image('logo.png'), // Fake file for testing
    ];

    // Send the POST request to create the employer
    $response = $this->post('/api/employers', $data);

    // Assert that the response status is 201 (Created)
    $response->assertStatus(201);

    // Optionally, check if the employer was actually created
    $this->assertDatabaseHas('employers', [
        'name' => 'Test Employer',
        'email' => 'test@employer.com',
    ]);

    // Check that the file was uploaded
    Storage::disk('public')->assertExists('logos/logo.png'); // Adjust path as needed
});

第 5 步:執行害蟲測試
執行您的 Pest 測試以確保一切按預期工作:

php artisan test --testsuit=Feature

結論

按照以下步驟,您可以使用 Pest 在 Laravel 中建立測試案例來驗證雇主記錄的創建,包括處理文件上傳。這種方法可確保您的應用程式按預期運行,並有助於在開發過程的早期發現任何問題。測試愉快!

以上是如何使用 Pest 在 Laravel 中建立測試案例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn