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

2024-08-06 0 233

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

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

先决条件

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

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

第 1 步:设置模型和关系

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

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

1

2

3

4

5

6

7

8

9

10

11

12

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

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 测试

创建测试文件并编写测试用例来验证雇主的创建,包括上传徽标。

创建测试文件

1

php artisan pest:test employercontrollertest

编写测试用例(tests/feature/employercontrollertest.php):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

<?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' =&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 测试以确保一切按预期工作

1

php artisan test --testsuit=Feature

结论

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

免责声明
1. 本站所有资源来源于用户上传和网络等,如有侵权请邮件联系本站整改team@lcwl.fun!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系本站工作人员处理!
6. 本站资源售价或VIP只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
8. 因人力时间成本问题,部分源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别!
9.本站所有源码资源都是经过本站工作人员人工亲测可搭建的,保证每个源码都可以正常搭建,但不保证源码内功能都完全可用,源码属于可复制的产品,无任何理由退款!

网站搭建学习网 C 如何使用 Pest 在 Laravel 中创建测试用例 https://www.xuezuoweb.com/9223.html

常见问题
  • 本站所有的源码都是经过平台人工部署搭建测试过可用的
查看详情
  • 购买源码资源时购买了带主机的套餐是指可以享受源码和所选套餐型号的主机两个产品,在本站套餐里开通主机可享优惠,最高免费使用主机
查看详情

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

Fa快捷助手
手机编程软件开发

在手机上用手点一点就能轻松做软件

去做软件
链未云主机
免备案香港云主机

开通主机就送域名的免备案香港云主机

去使用
链未云服务器
免备案香港云服务器

支持售后、超低价、稳定的免备案香港云服务器

去使用