Laravel event/listener 测试间歇性失败

Laravel event/listener test intermittently failing

我有一个非常简单的测试来检查我的事件增加了视频播放的次数

$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);

VideoPlaysWasStartedclass,我传视频

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);
    }