【问题标题】:Laravel unit testing if an event is triggered when an eloquent model event is triggeredLaravel 单元测试是否在触发 eloquent 模型事件时触发事件
【发布时间】:2023-03-22 13:18:01
【问题描述】:

我正在开发一个 Laravel 应用程序并在此过程中编写测试。现在,我在编写一个测试时遇到问题,该测试断言在触发 eloquent 模型事件时是否触发了事件。这就是我正在做的。

这是我的 ItemObserver 创建的函数

public function created(Item $item)
{
    event(new NewItemCreated($item));
}

如你所见,我在 eloquent 模型观察者的 created 事件中触发了一个事件。

如果我想断言测试中是否触发了事件,我必须伪造事件然后断言类似这样的东西。

Event::fake();
factory(Item::class)->create(); //created function of observer should be triggered but it will not be
Event::assertDispatched(NewItemCreated::class);

正如您在测试代码中看到的那样,我试图断言是否在创建项目时触发了事件。但是测试永远不会通过,因为观察者类的创建函数永远不会被调用,因为事件是在测试中伪造的。我该如何测试这种情况?

【问题讨论】:

  • 你把观察者绑定到模型了吗?

标签: laravel laravel-testing laravel-events


【解决方案1】:

只伪造你想测试的事件:

Event::fake([NewItemCreated::class]);

Relevant documentation.

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 2016-09-11
    • 2017-05-08
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多