【问题标题】:How to test that a job is released after a certain time when failing?失败时如何测试某个作业是否在一定时间后被释放?
【发布时间】:2020-03-21 16:49:11
【问题描述】:

当我有这样的工作时

class CheckVideoStatusJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $video;

    public function __construct(Video $video)
    {
        $this->video = $video;
    }

    public function handle(CheckStatusAction $action)
    {
        if (! $action->execute($this->video)) {
            $this->release(60);
        }
    }
}

我如何测试:当作业失败时,它将在 (60) 秒后释放回队列?

【问题讨论】:

    标签: laravel testing phpunit


    【解决方案1】:

    在我看来,你依靠 Laravel 自己的测试来确保发布方法的正常工作,并且在工作环境中不使用时间来测试它。如果您仍然想这样做,您只需要确保调用 release 即可。我会使用Mockery 进行部分模拟。

    此代码创建一个仅模拟释放方法并将视频传递给构造函数的类。

    $mock = \Mockery::mock(CheckVideoStatusJob::class, $video)->makePartial();
    
    // expects release call, once, parameter should be 60 returns null
    $mock->shouldReceive('release')->once()->with(60)->return(null);
    
    // action should offcourse secure that execute returns false
    $mock->handle($action);
    

    为了确保测试的安全,请使用带有 mockery 的断言,使用 mockery trait。

    use MockeryPHPUnitIntegration;
    

    【讨论】:

    • 现在我不确定这是否可行,因为当handle方法被调用时它是父类并且质疑 $this->release 将从那里做什么,今晚会测试它,留下答案,因为它可能会帮助到那时
    • 基于这个答案,解决方案应该可以工作stackoverflow.com/questions/48666043/…
    • 我喜欢它,使用这种方法确实很有意义。一个相关的问题我不想把它放在一个新的帖子里。我正在使用“retryUntil”函数(laravel.com/docs/6.x/queues#time-based-attempts),如何使用这种方法进行测试?
    • $mock->shouldReceive('retryUntil')->once()->with()->return(null);应该做的伎俩
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 2019-09-06
    相关资源
    最近更新 更多