Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Cara Membuat Kes Ujian dalam Laravel Menggunakan Perosak

Cara Membuat Kes Ujian dalam Laravel Menggunakan Perosak

WBOY
WBOYasal
2024-08-06 07:13:42935semak imbas

How to Create a Test Case in Laravel Using Pest

Menguji aplikasi Laravel anda adalah penting untuk memastikan kod anda berfungsi seperti yang diharapkan. Perosak ialah rangka kerja ujian untuk PHP, direka bentuk untuk menjadi minimalis dan mesra pengguna. Dalam catatan blog ini, kami akan meneruskan proses mencipta kes ujian dalam Laravel menggunakan Pest, memfokuskan pada contoh yang kami menguji penciptaan rekod Majikan, termasuk memuat naik logo.

Prasyarat

  • Aplikasi Laravel disediakan
  • Perosak dipasang dalam aplikasi Laravel anda

Jika anda belum memasang Pest lagi, anda boleh berbuat demikian dengan mengikuti panduan pemasangan Pest rasmi.

Langkah 1: Menyediakan Model dan Perhubungan

Pastikan model Pengguna dan Majikan anda disediakan dengan betul dengan perhubungan yang diperlukan.

Model Pengguna (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);
    }
}

Model Majikan (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);
    }
}

Langkah 2: Sediakan Kilang

Buat kilang untuk menjana data ujian.

Kilang Pengguna (pangkalan data/kilang/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),
        ];
    }
}

Kilang Majikan (pangkalan data/kilang/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')
        ];
    }
}

Langkah 3: Menulis Pengawal

Buat kaedah pengawal untuk mengendalikan penciptaan Majikan.

Pengawal Majikan (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);
    }
}

Langkah 4: Mencipta Ujian Perosak

Buat fail ujian dan tulis kes ujian untuk mengesahkan penciptaan Majikan, termasuk memuat naik logo.

Buat Fail Ujian:

php artisan pest:test EmployerControllerTest

Tulis Kes Ujian (ujian/Ciri/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
});

Langkah 5: Menjalankan Ujian Perosak Anda
Jalankan ujian Perosak anda untuk memastikan semuanya berfungsi seperti yang diharapkan:

php artisan test --testsuit=Feature

Kesimpulan

Dengan mengikut langkah ini, anda boleh membuat kes ujian dalam Laravel menggunakan Pest untuk mengesahkan penciptaan rekod Majikan, termasuk mengendalikan muat naik fail. Pendekatan ini memastikan aplikasi anda berkelakuan seperti yang diharapkan dan membantu menangani sebarang isu pada awal proses pembangunan. Selamat mencuba!

Atas ialah kandungan terperinci Cara Membuat Kes Ujian dalam Laravel Menggunakan Perosak. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn