Ranx99
3 months ago
379
3
Testing

How to test a failing job code

Posted 3 months ago by Ranx99

I have this job:

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

    public $file;

    public function __construct(File $file)
    {
        $this->file = $file;
    }

    public function handle()
    {
        $this->file->update([
            'status' => 'procssing',
        ]);

        $this->start();

        $this->file->update([
            'status' => 'success',
        ]);
    }

    public function failed(Exception $exception)
    {
        $this->file->update([
            'status' => 'un-procssed',
        ]);
    }

    protected function start()
    {
        return true;
    }
}

I am trying to test the code in the failed method:

/** @test */
public function it_will_set_status_to_un_procssed_when_failing()
{
    $file = factory(File::class)->create();

    $mock = Mockery::mock(ProcessFileJob ::class, [$file])->shouldAllowMockingProtectedMethods()->makePartial();
    $mock->shouldReceive('start')->once()->andThrow(new CustomException('test'));

    $mock->handle($file);

    $this->assertEquals('un-processed', $file->fresh()->status);
}

but this will always throw the CustomException and the test will fail.. even If I use withExceptionHandling method. I just want to test the code in the failed method to make sure when the job is failed the status of the file will change.

Please sign in or create an account to participate in this conversation.