0

0

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

王林

王林

发布时间:2024-08-06 14:39:11

|

308人浏览过

|

来源于dev.to

转载

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

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

先决条件

  • laravel 应用程序设置
  • pest 安装在你的 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):

CPWEB企业网站管理系统2.2 Beta
CPWEB企业网站管理系统2.2 Beta

CPWEB企业网站管理系统(以下称CPWEB)是一个基于PHP+Mysql架构的企业网站管理系统。CPWEB 采用模块化方式开发,功能强大灵活易于扩展,并且完全开放源代码,面向大中型站点提供重量级企业网站建设解决方案。CPWEB企业网站管理系统 2.2 Beta 测试版本,仅供测试,不建议使用在正式项目中,否则发生任何的后果自负。

下载
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):

 '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 中创建测试用例来验证雇主记录的创建,包括处理文件上传。这种方法可确保您的应用程序按预期运行,并有助于在开发过程的早期发现任何问题。测试愉快!

相关专题

更多
php文件怎么打开
php文件怎么打开

打开php文件步骤:1、选择文本编辑器;2、在选择的文本编辑器中,创建一个新的文件,并将其保存为.php文件;3、在创建的PHP文件中,编写PHP代码;4、要在本地计算机上运行PHP文件,需要设置一个服务器环境;5、安装服务器环境后,需要将PHP文件放入服务器目录中;6、一旦将PHP文件放入服务器目录中,就可以通过浏览器来运行它。

1987

2023.09.01

php怎么取出数组的前几个元素
php怎么取出数组的前几个元素

取出php数组的前几个元素的方法有使用array_slice()函数、使用array_splice()函数、使用循环遍历、使用array_slice()函数和array_values()函数等。本专题为大家提供php数组相关的文章、下载、课程内容,供大家免费下载体验。

1306

2023.10.11

php反序列化失败怎么办
php反序列化失败怎么办

php反序列化失败的解决办法检查序列化数据。检查类定义、检查错误日志、更新PHP版本和应用安全措施等。本专题为大家提供php反序列化相关的文章、下载、课程内容,供大家免费下载体验。

1212

2023.10.11

php怎么连接mssql数据库
php怎么连接mssql数据库

连接方法:1、通过mssql_系列函数;2、通过sqlsrv_系列函数;3、通过odbc方式连接;4、通过PDO方式;5、通过COM方式连接。想了解php怎么连接mssql数据库的详细内容,可以访问下面的文章。

948

2023.10.23

php连接mssql数据库的方法
php连接mssql数据库的方法

php连接mssql数据库的方法有使用PHP的MSSQL扩展、使用PDO等。想了解更多php连接mssql数据库相关内容,可以阅读本专题下面的文章。

1400

2023.10.23

html怎么上传
html怎么上传

html通过使用HTML表单、JavaScript和PHP上传。更多关于html的问题详细请看本专题下面的文章。php中文网欢迎大家前来学习。

1229

2023.11.03

PHP出现乱码怎么解决
PHP出现乱码怎么解决

PHP出现乱码可以通过修改PHP文件头部的字符编码设置、检查PHP文件的编码格式、检查数据库连接设置和检查HTML页面的字符编码设置来解决。更多关于php乱码的问题详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1439

2023.11.09

php文件怎么在手机上打开
php文件怎么在手机上打开

php文件在手机上打开需要在手机上搭建一个能够运行php的服务器环境,并将php文件上传到服务器上。再在手机上的浏览器中输入服务器的IP地址或域名,加上php文件的路径,即可打开php文件并查看其内容。更多关于php相关问题,详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1303

2023.11.13

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Laravel---API接口
Laravel---API接口

共7课时 | 0.6万人学习

PHP自制框架
PHP自制框架

共8课时 | 0.6万人学习

PHP面向对象基础课程(更新中)
PHP面向对象基础课程(更新中)

共12课时 | 0.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号