dping1968 2018-04-17 10:53
浏览 43
已采纳

测试Eloquent Observer的方法是否触发事件

The app I am working on fires an event, when one of the Eloquent model attributes is updated.

The Eloquent model is called Job and it is supposed to fire JobCustomerTotalAmountDueChanged when the duration attribute is updated. I have the following code in the JobObserver:

public function saved(Job $job)
{
    if ($job->isDirty('duration')) {
        event(new JobCustomerTotalAmountDueChanged($job));
    }
}

When I try to test it using Event::fake, Eloquent events are not being fired, which means that the code in saved method is never execured. From what I see the assertDispatched and assertNotDispatched methods are only available for faked events. Is there a way to assert that a particular event is/is not fired without Event::fake?

  • 写回答

1条回答 默认 最新

  • douchang6770 2018-04-17 14:39
    关注

    The solution turned out to be very easy after all:

    Laravel lets you specify which events should be faked, as an argument to fake method. In my example:

    Event::fake([JobCustomerTotalAmountDueChanged::class])
    

    All of the other events are being triggered and handled. Also, you can make assertions only with reference to events passed as argument to fake method. If you don't pass any argument, Laravel will try to 'fake' every event in the app.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题