我正在开发一个 Laravel 应用程序。我在我的应用程序中使用 Laravel 广播。我现在要做的是尝试测试是否在 Laravel 中广播了一个事件。
我正在广播这样的事件:
broadcast(new NewItemCreated($item));
我想测试是否广播了该事件。我该如何测试它?我的意思是在单元测试中。我想做类似的事情
Broadcast::assertSent(NewItemCreated::class)
附加信息
该事件在创建项目时触发的观察者事件中广播。
我正在开发一个 Laravel 应用程序。我在我的应用程序中使用 Laravel 广播。我现在要做的是尝试测试是否在 Laravel 中广播了一个事件。
我正在广播这样的事件:
broadcast(new NewItemCreated($item));
我想测试是否广播了该事件。我该如何测试它?我的意思是在单元测试中。我想做类似的事情
Broadcast::assertSent(NewItemCreated::class)
该事件在创建项目时触发的观察者事件中广播。
我认为你可以通过Laravel 中的 Mocking 来实现这一点(Event Fake)
<?php
namespace Tests\Feature;
use App\Events\NewItemCreated;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* Test create item.
*/
public function testOrderShipping()
{
// this is important
Event::fake();
// Perform item creation...
Event::assertDispatched(NewItemCreated::class, function ($e) {
return $e->name === 'test' ;
});
// Assert an event was dispatched twice...
Event::assertDispatched(NewItemCreated::class, 2);
// Assert an event was not dispatched...
Event::assertNotDispatched(NewItemCreated::class);
}
}
我认为您可以或多或少地将广播视为事件,因此您可以参考文档的这一部分。
如果您使用 广播您的事件broadcast($event),该函数将调用event广播工厂的方法,您可以模拟该方法,如下所示:
$this->mock(\Illuminate\Contracts\Broadcasting\Factory::class)
->shouldReceive('event')
->with(NewItemCreated::class)
->once();
// Processing logic here
不确定这是否是实现这一目标的最佳方法,但它是唯一对我有用的方法。