【问题标题】:Laravel event/listener test intermittently failingLaravel 事件/监听器测试间歇性失败
【发布时间】:2021-05-27 17:33:21
【问题描述】:

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

$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

我错过了什么?

【问题讨论】:

  • 这表明它没有按预期在数据库中找到视频。你确定 factory() 调用没有失败吗?你能可靠地转储($video);插入后看到预期的数据?是否有任何模型事件或任何可能会在创建视频后从数据库中更改或删除视频?
  • 是的,如果我在创建后转储$video,它会显示模型,它是间歇性的,这让我很烦恼。这是由前端的 JavaScript 通过捕获 vimeo_id 触发的 - 可能会看看我们是否可以更改它以获取模型。
  • vimeo_id 是如何设置的,是否有可能无法设置?您可能会考虑传递 id 字段并通过它从数据库中检索它。
  • 它来自模型。我刚刚弄清楚为什么它会间歇性地失败???? .我忘记了我在检查is_published 的模型上的范围以及关于它是否应该可用的时间戳。测试失败是正确的,因为未发布的视频不应该可用。谢谢你躲避詹姆斯。

标签: laravel event-handling tdd listener


【解决方案1】:

我的问题是我忘记了我应用到模型以检查视频发布状态的范围。

我的视频工厂设置为随机分配 is_published 标志为真/假。所以当然,有时如果视频没有发布,那么事件侦听器在查找时会得到空结果。

解决方案是覆盖工厂创建并改进我的测试

/** @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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 2013-07-04
    相关资源
    最近更新 更多