使用 Event::fake() 拦截事件后,可通过 assertDispatched 断言事件被触发、assertDispatchedTimes 验证触发次数、assertNotDispatched 确保未触发,并可结合闭包验证事件数据。

示例代码:
use Illuminate\Support\Facades\Event;
use App\Events\UserRegistered;
public function test_user_registration_dispatches_event()
{
Event::fake();
$this->expectsEvents(UserRegistered::class);
// 执行触发事件的操作
$this->post('/register', [
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => 'secret'
]);
}
常用方法包括:
use Illuminate\Support\Facades\Event;
use App\Events\OrderShipped;
public function test_order_shipment_dispatches_event()
{
Event::fake();
// 执行业务逻辑
$order = Order::factory()->create();
$order->ship();
// 断言事件被触发
Event::assertDispatched(OrderShipped::class);
// 断言事件触发一次
Event::assertDispatchedTimes(OrderShipped::class, 1);
// 断言事件带有特定数据
Event::assertDispatched(OrderShipped::class, function ($event) use ($order) {
return $event->order->id === $order->id;
});
}
Event::fake(); // 执行某些操作 $user = User::factory()->make(); $user->save(); // 假设未触发 UserRegistered Event::assertNotDispatched(UserRegistered::class);
以上就是laravel怎么在测试中断言(assert)一个事件被分发_laravel测试中事件断言方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号