【问题标题】:How can I test laravel job's second try logic which is using attempts function如何测试使用尝试功能的 laravel 作业的第二次尝试逻辑
【发布时间】:2020-12-19 10:38:19
【问题描述】:

我有一个排队的作业类,由于backoff() 方法,它呈指数级后退。我想测试backoff() 方法是否正确。它应该在每次重试后创建2, 4, 8, 16 等等。由于attempts() 函数属于InteractsWithQueue trait 并从更深的RedisJob 类'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());
        }
    }   
}

【问题讨论】:

    标签: php laravel unit-testing phpunit laravel-jobs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 2016-10-17
      • 2021-12-19
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多