信息发布→ 登录 注册 退出

laravel怎么在测试中模拟通知的发送(Notification Fake)_laravel测试中Notification Fake方法

发布时间:2025-10-18

点击量:
在 Laravel 测试中,使用 Notification::fake() 可模拟通知发送行为,避免实际调用外部服务。首先调用 Notification::fake() 拦截通知,然后通过 assertSentTo 等方法断言用户是否收到指定通知,如 Notification::assertSentTo($user, AccountApprovedNotification::class);支持验证发送次数、未发送情况及通知参数内容,例如通过闭包检查通知数据或通道,确保 order_id 正确或包含 mail 通道;同一测试中可多次调用 fake() 清除记录以隔离场景。该方式提升测试速度与稳定性,无需依赖真实邮件或短信服务。

在 Laravel 测试中,你不需要实际发送通知(Notification),而是可以通过 Notification Facade 的 Fake 功能来模拟通知的发送行为。这样可以避免调用真实邮件、短信或第三方服务,同时还能验证通知是否被正确分发给目标用户。

1. 使用 Notification::fake() 模拟通知

在测试开始前调用 Notification::fake(),Laravel 会拦截所有通知发送请求,不会真正触发任何外部操作。

示例:

use Illuminate\Support\Facades\Notification;
use Tests\TestCase;

class UserNotificationTest extends TestCase
{
    public function test_notification_sent_to_user()
    {
        Notification::fake(); // 启用通知模拟

        $user = factory(User::class)->create();

        // 触发某个会发送通知的操作
        $user->notify(new AccountApprovedNotification());

        // 断言指定用户收到了指定通知
        Notification::assertSentTo($user, AccountApprovedNotification::class);
    }
}

2. 常用断言方法

启用 fake 后,你可以使用以下方法验证通知行为:

  • assertSentTo($notifiable, $notification):断言某个可通知对象收到了指定通知。
  • assertNotSentTo($notifiable, $notification):断言某个对象没有收到该通知。
  • assertNothingSent():断言没有任何通知被发送。
  • assertSentToTimes($notifiable, $notification, $times):断言通知被发送了指定次数。

示例:验证发送次数

Notification::assertSentToTimes($user, AccountApprovedNotification::class, 1);

3. 检查通知的参数内容

你还可以检查通知实例中的数据,确保传递的内容正确。

Notification::assertSentTo(
    $user,
    AccountApprovedNotification::class,
    function ($notification, $channels) use ($expectedData) {
        return $notification->order->id === $expectedData['order_id'];
    }
);

上面的闭包接收通知实例和通道数组,返回 true 表示匹配成功。可用于验证通知携带的数据是否符合预期。

4. 针对不同通道的测试

Laravel 通知支持多种通道(如 mail、database、broadcast 等)。你可以验证通知是否通过特定通道发送。

Notification::assertSentTo(
    $user,
    AccountApprovedNotification::class,
    function ($notification, $channels) {
        return in_array('mail', $channels); // 确保通过邮件通道发送
    }
);

5. 清除已记录的通知

如果你在同一个测试中需要分别测试多个场景,可以使用 Notification::fake() 重置记录:

Notification::fake(); // 清空之前记录
// 执行新操作并断言

每次调用 fake() 都会清空之前的发送记录,适合隔离不同测试逻辑。

基本上就这些。只要记得先调用 Notification::fake(),再执行业务逻辑,最后用断言验证行为即可。这种方式让测试更快速、稳定,且不依赖外部服务。

标签:# 你可以  # 你不  # 你还  # 没有任何  # 还能  # 多个  # 如果你  # 清空  # 收到了  # 测试中  # laravel  # database  # 对象  # 闭包  # class  # mail  # ai  # app  # cad  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!