如何解决Laravel 事件/侦听器测试间歇性失败
$video = Video::factory()->create([
'uuid' => 'xxx','slug' => 'xxx'
]);
$event = new VideoPlayWasstarted($video->vimeo_id);
$listener = new IncreaseVideoStartedCount;
$listener->handle($event);
$this->assertEquals(++$video->started_plays,$video->fresh()->started_plays);
在VideoPlaysWasstarted
课上,我传了视频
public $videoId;
public function __construct($videoId)
{
$this->videoId = $videoId;
}
然后在侦听器 handle
方法中
public function handle(VideoPlayWasstarted $event)
{
$video = Video::where('vimeo_id',$event->videoId)->first();
$video->increaseStartedplays();
}
但是,在运行我的测试时间歇性地,$video
返回为 null 导致 Error : Call to a member function increaseStartedplays() on null
我错过了什么?
解决方法
我的问题是我忘记了我应用于模型以检查视频发布状态的范围。
我的视频工厂设置为将 is_published
标志随机分配为 true/false。所以当然,有时如果视频没有发布,那么事件侦听器在查找时会得到空结果。
解决方案是覆盖工厂创建并改进我的测试
/** @test */
public function when_a_user_starts_a_published_video_it_increments_the_start_count_by_one()
{
$video = Video::factory()->create([
'is_published' => 1,'created_at' => Carbon::now(),]);
$event = new VideoPlayWasStarted($video->vimeo_id);
$listener = new IncreaseVideoStartedCount;
$listener->handle($event);
$this->assertEquals($video->started_plays + 1,$video->fresh()->started_plays);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。