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

测试您的 laravel 应用程序对于确保您的代码按预期工作至关重要。 pest 是一个 php 测试框架,设计简约且用户友好。在这篇博文中,我们将逐步使用 pest 在 laravel 中创建一个测试用例,重点关注一个测试雇主记录创建的

如何使用 pest 在 laravel 中创建测试用例

测试您的 laravel 应用程序对于确保您的代码按预期工作至关重要。 pest 是一个 php 测试框架,设计简约且用户友好。在这篇博文中,我们将逐步使用 pest 在 laravel 中创建一个测试用例,重点关注一个测试雇主记录创建的示例,包括上传徽标。

先决条件

  • laravel 应用程序设置
  • pest 安装在你的 laravel 应用程序中

如果您还没有安装 pest,您可以按照 pest 官方安装指南进行安装。

第 1 步:设置模型和关系

确保您的用户和雇主模型正确设置并具有必要的关系。

用户模型(app/models/user.php):

namespace appmodels;

use illuminatefoundationauthuser as authenticatable;
use illuminatedatabaseeloquentrelationshasone;

class user extends authenticatable
{
    public function employer(): hasone
    {
        return $this->hasone(employer::class);
    }
}

登录后复制

雇主模型(app/models/employer.php):

namespace appmodels;

use illuminatedatabaseeloquentmodel;
use illuminatedatabaseeloquentrelationsbelongsto;

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 databasefactories;

use appmodelsuser;
use illuminatedatabaseeloquentfactoriesfactory;
use illuminatesupportstr;

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 databasefactories;

use appmodelsemployer;
use illuminatedatabaseeloquentfactoriesfactory;
use illuminatehttpuploadedfile;

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 apphttpcontrollers;

use illuminatehttprequest;
use appmodelsemployer;
use illuminatesupportfacadesstorage;

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 illuminatefoundationtestingrefreshdatabase;
use illuminatesupportfacadesauth;
use appmodelsuser;
use appmodelsemployer;
use illuminatehttpuploadedfile;
use illuminatesupportfacadesstorage;

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' =&gt; 'test@employer.com',
        'phone' =&gt; '1234567890',
        'address' =&gt; '123 employer st',
        'city' =&gt; 'employer city',
        'website' =&gt; 'https://www.employer.com',
    ];

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

    // assert that the response status is 401 (unauthorized)
    $response-&gt;assertstatus(401);

    // optionally, check that the employer was not created
    $this-&gt;assertdatabasemissing('employers', [
        'name' =&gt; 'test employer',
        'email' =&gt; 'test@employer.com',
    ]);
});

it('creates a new employer for authenticated user', function () {
    // create a user and log them in
    $user = user::factory()-&gt;create();
    auth::login($user);

    // define the data to be sent in the post request
    $data = [
        'name' =&gt; 'test employer',
        'email' =&gt; 'test@employer.com',
        'phone' =&gt; '1234567890',
        'address' =&gt; '123 employer st',
        'city' =&gt; 'employer city',
        'website' =&gt; 'https://www.employer.com',
    ];

    // send the post request to create the employer
    $response = $this-&gt;post('/api/employers', $data);

    // assert that the response status is 201 (created)
    $response-&gt;assertstatus(201);

    // assert that the employer was created
    $this-&gt;assertdatabasehas('employers', [
        'name' =&gt; 'test employer',
        'email' =&gt; 'test@employer.com',
    ]);
});

it('creates a new employer with a logo', function () {
    // create a user and log them in
    $user = user::factory()-&gt;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' =&gt; 'test employer',
        'email' =&gt; 'test@employer.com',
        'phone' =&gt; '1234567890',
        'address' =&gt; '123 employer st',
        'city' =&gt; 'employer city',
        'website' =&gt; 'https://www.employer.com',
        'logo' =&gt; uploadedfile::fake()-&gt;image('logo.png'), // fake file for testing
    ];

    // send the post request to create the employer
    $response = $this-&gt;post('/api/employers', $data);

    // assert that the response status is 201 (created)
    $response-&gt;assertstatus(201);

    // optionally, check if the employer was actually created
    $this-&gt;assertdatabasehas('employers', [
        'name' =&gt; 'test employer',
        'email' =&gt; 'test@employer.com',
    ]);

    // check that the file was uploaded
    storage::disk('public')-&gt;assertexists('logos/logo.png'); // adjust path as needed
});

登录后复制

第 5 步:运行害虫测试
运行您的 pest 测试以确保一切按预期工作:

php artisan test --testsuit=Feature

登录后复制

结论

按照以下步骤,您可以使用 pest 在 laravel 中创建测试用例来验证雇主记录的创建,包括处理文件上传。这种方法可确保您的应用程序按预期运行,并有助于在开发过程的早期发现任何问题。测试愉快!

以上就是如何使用 Pest 在 Laravel 中创建测试用例的详细内容,更多请关注叮当号网其它相关文章!

文章来自互联网,只做分享使用。发布者:pansz,转转请注明出处:https://www.dingdanghao.com/article/686926.html

(0)
上一篇 2024-08-06 14:46
下一篇 2024-08-06 14:46

相关推荐

联系我们

在线咨询: QQ交谈

邮件:442814395@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信公众号