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

在 Laravel 测试中,你不需要实际发送通知(Notification),而是可以通过 Notification Facade 的 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);
    }
}
启用 fake 后,你可以使用以下方法验证通知行为:
示例:验证发送次数
Notification::assertSentToTimes($user, AccountApprovedNotification::class, 1);
你还可以检查通知实例中的数据,确保传递的内容正确。
Notification::assertSentTo(
    $user,
    AccountApprovedNotification::class,
    function ($notification, $channels) use ($expectedData) {
        return $notification->order->id === $expectedData['order_id'];
    }
);
上面的闭包接收通知实例和通道数组,返回 true 表示匹配成功。可用于验证通知携带的数据是否符合预期。
Laravel 通知支持多种通道(如 mail、database、broadcast 等)。你可以验证通知是否通过特定通道发送。
Notification::assertSentTo(
    $user,
    AccountApprovedNotification::class,
    function ($notification, $channels) {
        return in_array('mail', $channels); // 确保通过邮件通道发送
    }
);
如果你在同一个测试中需要分别测试多个场景,可以使用 Notification::fake() 重置记录:
Notification::fake(); // 清空之前记录 // 执行新操作并断言
每次调用 fake() 都会清空之前的发送记录,适合隔离不同测试逻辑。
基本上就这些。只要记得先调用 Notification::fake(),再执行业务逻辑,最后用断言验证行为即可。这种方式让测试更快速、稳定,且不依赖外部服务。
以上就是laravel怎么在测试中模拟通知的发送(Notification Fake)_laravel测试中Notification Fake方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号