我如何测试 laravel 作业的第二个尝试逻辑,它使用了 attempts 函数

How can I test laravel job's second try logic which is using attempts function

我有一个排队的作业 class 由于 backoff() 方法,它以指数方式后退。我想测试 backoff() 方法是否正常工作。它应该在每次重试后创建 2, 4, 8, 16 等等。由于 attempts() 函数属于 InteractsWithQueue 特征并从更深的 RedisJob class' decoded 有效载荷中读取尝试计数,我找不到合适的方法来测试一下。

有什么帮助吗?

class AJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public $tries = 10; 

    public function backoff()
    {
        return pow(2, $this->attempts());
    }

    public function handle()
    {
        try{
            //Some logic
        }
        catch(Exception $e){
            $this->release($this->backoff());
        }
    }   
}

我解决了这个问题。这是解决方案。

public function test_backoff_after_fifth_attempt()
    {
        /** @var RedisJob $mockRedisJob */
        $mockRedisJob = $this->mock(
            RedisJob::class,
            function (MockInterface $mock) {
                $mock->shouldReceive('attempts')->once()
                     ->andReturn(5);
            }
        );

        $job = new SendMailJob(new Mail());
        $job->setJob($mockRedisJob);

        $this->assertEquals(32, $job->backoff());
    }