Laravel Laravel
  • 前言

    • 发行说明
    • 升级向导
    • 贡献导引
    • API 文档
  • 入门指南

    • 安装
    • 配置
    • 文件夹结构
    • Homestead
    • Valet
  • 架构思想

    • 请求生命周期
    • 服务容器
    • 服务提供者
    • Facades:门面
    • Contracts:契约
  • 基础功能

    • 路由
    • 中间件
    • CSRF 保护
    • 控制器
    • 请求
    • 响应
    • 视图
    • Session
    • 表单验证
    • 错误 & 日志
  • 前端开发

    • Blade 模板
    • 本地化
    • 前端脚手架
    • 编译资源
  • 安全

    • 身份认证
    • API 身份认证
    • 授权
    • 加密
    • 哈希
    • 重置密码
  • 深入话题

    • Artisan 命令行
    • 广播
    • 缓存
    • 集合
    • 事件
    • 文件存储
    • 辅助函数
    • Mail
    • 消息通知
    • 扩展包开发
    • 队列
    • 任务调度
  • 数据库

    • 快速入门
    • 查询构造器
    • 分页
    • 数据库迁移
    • 数据填充
    • Redis
  • Eloquent ORM

    • 快速入门
    • 关联关系
    • Eloquent 集合
    • 修改器
    • 序列化
  • 测试

    • 快速入门
    • HTTP 测试
    • 浏览器测试
    • 数据库测试
    • 测试模拟器Mocking
  • 官方扩展包

    • Cashier
    • Envoy部署工具
    • PassportOAuth 认证
    • Scout全文搜索
    • Socialite社会化登录
Icon

提示 您正在浏览旧版本的 Laravel 的文档. 请考虑将你的项目升级到 Laravel 11.x.

0 0

测试模拟器
5.4
8.x 7.x 6.x 5.8 5.7 5.6 5.5 5.4 5.3 5.2 5.1

Laravel 5.4 中文文档 /

未匹配的标注
本文档最新版为 8.x,旧版本可能放弃维护,推荐阅读最新版!

Laravel 测试之:测试模拟器

  • 介绍
  • 任务模拟
  • 事件模拟
  • 邮件模拟
  • 通知模拟
  • 队列模拟
  • Storage 模拟
  • Facades 模拟

介绍

测试 Laravel 应用时,有时候你可能想要「模拟」实现应用的部分功能的行为,从而避免该部分在测试过程中真正执行。例如,控制器执行过程中会触发一个事件( Events ),你想要模拟这个事件的监听器,从而避免该事件在测试这个控制器时真正执行。如上可以让你仅测试控制器的 HTTP 响应情况,而不用去担心触发事件。当然,你可以在单独的测试中测试该事件的逻辑。

Laravel 针对事件、任务和 facades 的模拟提供了开箱即用的辅助函数。这些辅助函数基于 Mockery 封装而成,使用非常简单,无需你手动调用复杂的 Mockery 函数。当然,你也可以使用 Mockery 或者 PHPUnit 创建自己的模拟器。

任务模拟

你可以使用 Bus facade 的 fake 方法来模拟任务执行,测试的时候任务不会被真实执行。使用 fakes 的时候,断言一般出现在测试代码的后面:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Jobs\ShipOrder;
use Illuminate\Support\Facades\Bus;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    public function testOrderShipping()
    {
        Bus::fake();

        // 处理订单发货...

        Bus::assertDispatched(ShipOrder::class, function ($job) use ($order) {
            return $job->order->id === $order->id;
        });

        // 断言任务并没有被执行...
        Bus::assertNotDispatched(AnotherJob::class);
    }
}

事件模拟

你可以使用 Event facade 的 fake 方法来模拟事件监听,测试的时候不会触发事件监听器运行。然后你就可以断言事件运行了,甚至可以检查它们收到的数据。使用 fakes 的时候,断言一般出现在测试代码的后面:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Events\OrderShipped;
use App\Events\OrderFailedToShip;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * 测试订单发货.
     */
    public function testOrderShipping()
    {
        Event::fake();

        // 处理订单发货...

        Event::assertDispatched(OrderShipped::class, function ($e) use ($order) {
            return $e->order->id === $order->id;
        });

        Event::assertNotDispatched(OrderFailedToShip::class);
    }
}

邮件模拟

你可以使用 Mail facade 的 fake 方法来模拟邮件发送,测试时不会真的发送邮件。然后你可以断言 mailables 发送给了用户,甚至可以检查他们收到的数据. 使用 fakes 时,断言一般在测试代码的后面:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Mail\OrderShipped;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    public function testOrderShipping()
    {
        Mail::fake();

        // 处理订单发货...

        Mail::assertSent(OrderShipped::class, function ($mail) use ($order) {
            return $mail->order->id === $order->id;
        });

        // 断言一封邮件已经发送给了指定用户...
        Mail::assertSent(OrderShipped::class, function ($mail) use ($user) {
            return $mail->hasTo($user->email) &&
                   $mail->hasCc('...') &&
                   $mail->hasBcc('...');
        });

        // 断言 mailable 没有发送...
        Mail::assertNotSent(AnotherMailable::class);
    }
}

通知模拟

你可以使用 Notification facade 的 fake 方法来模拟通知发送,测试的时候并不会真的发送通知。然后你可以断言 通知 已经发送给你的用户,甚至可以检查他们收到的数据。使用 fakes 时, 断言一般出现在测试代码的后面.

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Notifications\OrderShipped;
use Illuminate\Support\Facades\Notification;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    public function testOrderShipping()
    {
        Notification::fake();

        // 处理订单发货...

        Notification::assertSentTo(
            $user,
            OrderShipped::class,
            function ($notification, $channels) use ($order) {
                return $notification->order->id === $order->id;
            }
        );

        // 断言通知已经发送给了指定用户...
        Notification::assertSentTo(
            [$user], OrderShipped::class
        );

        // 断言通知没有发送...
        Notification::assertNotSentTo(
            [$user], AnotherNotification::class
        );
    }
}

队列模拟

你可以使用 Queue facade 的 fake 方法来模拟任务队列,测试的时候并不会真的把任务放入队列。然后你可以断言任务被放进了队列,甚至可以检查它们收到的数据。使用 fakes 的时候,断言一般出现在测试代码的后面。

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Jobs\ShipOrder;
use Illuminate\Support\Facades\Queue;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    public function testOrderShipping()
    {
        Queue::fake();

        // 处理订单发货...

        Queue::assertPushed(ShipOrder::class, function ($job) use ($order) {
            return $job->order->id === $order->id;
        });

        // 断言任务进入了指定队列
        Queue::assertPushedOn('queue-name', ShipOrder::class);

        // 断言任务没有进入队列
        Queue::assertNotPushed(AnotherJob::class);
    }
}

Storage 模拟

利用 Storage facade 的 fake 方法,你可以轻松地生成一个模拟的磁盘,结合 UploadedFile 类的文件生成工具,极大地简化了文件上传测试。例如:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    public function testAvatarUpload()
    {
        Storage::fake('avatars');

        $response = $this->json('POST', '/avatar', [
            'avatar' => UploadedFile::fake()->image('avatar.jpg')
        ]);

        // 断言文件已存储
        Storage::disk('avatars')->assertExists('avatar.jpg');

        // 断言文件不存在
        Storage::disk('avatars')->assertMissing('missing.jpg');
    }
}

Facades 模拟

不同于传统的静态函数的调用, facades 也是可以被模拟的,相对静态函数来说这是个巨大的优势,即使你在使用依赖注入,测试时依然会非常方便。在很多测试中,你可能经常想在控制器中模拟对 Laravel facade 的调用。比如下面控制器中的行为:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;

class UserController extends Controller
{
    /**
     * 显示网站的所有用户
     *
     * @return Response
     */
    public function index()
    {
        $value = Cache::get('key');

        //
    }
}

我们可以通过 shouldReceive 方法来模拟 Cache facade ,此函数会返回一个 Mockery 实例,由于对 facade 的调用实际上都是由 Laravel 的 服务容器 管理的,所以 facade 能比传统的静态类表现出更好的测试便利性。接下来,让我们来模拟一下 Cache facade 的 get 方法的调用:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class UserControllerTest extends TestCase
{
    public function testGetIndex()
    {
        Cache::shouldReceive('get')
                    ->once()
                    ->with('key')
                    ->andReturn('value');

        $response = $this->get('/users');

        // ...
    }
}

{note} 不可以模拟 Request facade,测试时,如果需要传递指定的数据请使用 HTTP 辅助函数,例如 get 和 post。类似的,请在你的测试中通过调用 Config::set 来模拟 Config facade。


上一篇 下一篇

成为Laravel合作伙伴

Laravel Partners是提供一流Laravel开发和咨询服务的精英商店。我们每个合作伙伴都可以帮助您制定一个精美,结构完善的项目.

我们的伙伴
Laravel
亮点
  • Our Team
  • 发布说明
  • 入门
  • 路由
  • Blade 模板
  • 身份验证
  • 用户授权
  • Artisan 控制台
  • 数据库
  • Eloquent ORM
  • 测试
资源
  • Laravel Bootcamp
  • Laracasts
  • Laravel News
  • Laracon
  • Laracon EU
  • Laracon India
  • Jobs
  • Forums
  • Trademark
  • 版本发布时间
  • 包开发
  • 命令行应用
  • TALL stack全栈开发
  • Blade UI Kit
  • 前端资源构建
伙伴
  • WebReinvent
  • Vehikl
  • Tighten
  • 64 Robots
  • Active Logic
  • Byte 5
  • Curotec
  • Cyber-Duck
  • DevSquad
  • Jump24
  • Kirschbaum
生态系统
  • Cashier
  • Dusk
  • Echo
  • Envoyer
  • Forge
  • Horizon
  • Nova
  • Octane
  • Sail
  • Sanctum
  • Scout
  • Spark
  • Telescope
  • Valet
  • Vapor

Laravel是一个具有表达力,优雅语法的Web应用程序框架。我们认为,发展必须是一种令人愉悦的创造力,才能真正实现。Laravel试图通过减轻大多数Web项目中使用的常见任务来减轻开发的痛苦.

Laravel是Taylor Otwell的商标.
Copyright © 2011-2025 Laravel中文网 LLC.

  • Twitter
  • GitHub
  • Discord
Laravel 全栈开发网 推荐使用阿里云 按Ctrl+D试试