如何使用 Pest 在 Laravel 中创建测试用例

WBOY
发布: 2024-08-06 07:13:42
原创
934 人浏览过

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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!