使用Queue :: fake()测试监听器 [英] Testing listeners with Queue::fake()
问题描述
我的Laravel 5.5应用程序具有 Product
模型. Product
模型具有一个 dispatchesEvents
属性,如下所示:
My Laravel 5.5 application has a Product
model. The Product
model has a dispatchesEvents
property that looks like this:
/**
* The event map for the model.
*
* @var array
*/
protected $dispatchesEvents = [
'created' => ProductCreated::class,
'updated' => ProductUpdated::class,
'deleted' => ProductDeleted::class
];
我还有一个名为 CreateProductInMagento
的侦听器,该侦听器映射到 EventServiceProvider
中的 ProductCreated
事件.该侦听器实现 ShouldQueue
接口.
I also have a listener that is called CreateProductInMagento
which is mapped to the ProductCreated
event in the EventServiceProvider
. This listener implements the ShouldQueue
interface.
创建产品时,将触发 ProductCreated
事件,并将 CreateProductInMagento
侦听器推入队列并运行.
When a product is created, the ProductCreated
event is fired and the CreateProductInMagento
listener is pushed to the queue and is run.
我现在正尝试为所有这些编写测试.这是我所拥有的:
I am now trying to write a test for all of this. Here is what I have:
/** @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);
}
但是我得到一个预期的[App \ Listeners \ Magento \ Product \ CreateProductInMagento]作业未推送.
错误消息.
But I get a The expected [App\Listeners\Magento\Product\CreateProductInMagento] job was not pushed.
error message.
如何使用Laravel的 Queue :: fake()
方法测试可排队的侦听器?
How do I test queueable listeners using Laravel's Queue::fake()
method?
推荐答案
此处的问题是,侦听器不是推送到队列的作业.取而代之的是,有一个 Illuminate \ Events \ CallQueuedListener
作业排队,并且在解析后将依次调用适当的侦听器.
The problem here is that the listener is not the job pushed to the queue. Instead, there's a Illuminate\Events\CallQueuedListener
job that is queued and will in turn call the appropriate listener when resolved.
所以您可以这样声明:
Queue::assertPushed(CallQueuedListener::class, function ($job) {
return $job->class == CreateProductInMagento::class;
});
这篇关于使用Queue :: fake()测试监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!