Skip to content
Advertisement

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

I have a queued job class which backs off exponentially thanks to the backoff() method. I want to test that backoff() method works right. It should create 2, 4, 8, 16 and so on after each retry. Since attempts() function belongs to the InteractsWithQueue trait and reads the attempt count from the deeper RedisJob class’ decoded payload, I could not find a proper way to test this.

Any help?

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

Advertisement

Answer

I solved the problem. Here is the solution.

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());
    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement