gpt4 book ai didi

php - 使用 Queue::fake() 测试监听器

转载 作者:可可西里 更新时间:2023-10-31 22:12:15 24 4
gpt4 key购买 nike

我的 Laravel 5.5 应用程序有一个 Product 模型。 Product 模型有一个 dispatchesEvents 属性,如下所示:

/**
* The event map for the model.
*
* @var array
*/
protected $dispatchesEvents = [
'created' => ProductCreated::class,
'updated' => ProductUpdated::class,
'deleted' => ProductDeleted::class
];

我还有一个名为 CreateProductInMagento 的监听器,它映射到 EventServiceProvider 中的 ProductCreated 事件。此监听器实现了 ShouldQueue 接口(interface)。

创建产品时,将触发 ProductCreated 事件并将 CreateProductInMagento 监听器推送到队列并运行。

我现在正在尝试为所有这些编写测试。这是我所拥有的:

/** @test */
public function a_created_product_is_pushed_to_the_queue_so_it_can_be_added_to_magento()
{
Queue::fake();

factory(Product::class)->create();

Queue::assertPushed(CreateProductInMagento::class);
}

但我得到了一个 The expected [App\Listeners\Magento\Product\CreateProductInMagento] job was not pushed. 错误消息。

如何使用 Laravel 的 Queue::fake() 方法测试队列监听器?

最佳答案

这里的问题是监听器不是推送到队列的作业。取而代之的是,有一个 Illuminate\Events\CallQueuedListener 作业已排队,并会在解析时依次调用适当的监听器。

所以你可以这样做你的断言:

Queue::assertPushed(CallQueuedListener::class, function ($job) {
return $job->class == CreateProductInMagento::class;
});

关于php - 使用 Queue::fake() 测试监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48083893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com