【问题标题】:Is there a way to fake specific event listeners when testing Laravel?在测试 Laravel 时有没有办法伪造特定的事件监听器?
【发布时间】:2021-11-03 05:47:55
【问题描述】:

我有一个包含多个侦听器的事件,其中一个会发送通知。我想在不运行不相关的侦听器的情况下对其进行测试。

// EventServiceProvider

protected $listen = [

    ProductionStarted::class => [
        StartOtherTasks::class,
        SendNotifications::class,
    ],
];

这是来自测试的 sn-p。调度事件时的问题是,它的所有侦听器都在运行(在这种情况下为StartOtherTasks侦听器)我不希望它侦听。

public function test_starting_production_sends_notification()
{
    event(new ProductionStarted());

    Notification::fake();

    Notification::assertSentTo(
        $notifiable,
        NotifyBatchStarted::class,
    );
}

【问题讨论】:

  • 你不这样做,你只是做一个功能测试并伪造事件,所以它不会触发监听器,如果你想专门测试一个监听器,你只需创建一个单元测试并运行在测试中监听事件,就是这样!

标签: laravel phpunit laravel-8


【解决方案1】:

你可以像这样触发一个特定的监听器

$listener = new StartOtherTasks();
$listener->handle(new ProductionStarted());

【讨论】:

    猜你喜欢
    • 2019-05-09
    • 1970-01-01
    • 2022-06-21
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 2011-12-21
    相关资源
    最近更新 更多