Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RoniWasHere's avatar

Testing Job Logic

I have a simple job that fails in a certain situation. I want to write a test the captures that failed logic to make sure the logic never gets broken.

class MyJob extends Job
{
		public function handle() {
				$latestAccessToken = AccessToken::latest('expires_at')->first();
				if (!$this->tokenIsValid($latestAccessToken)) {
		            $this->fail(new MyException("No access token or token is has expired"));
		            return;
		        }
		}
}

How would you write a test to capture the fail method?

I've tried with Queue::fake - but that is only for testing if the job has entered the queue. I've tried with try ... catch but that doesn't catch the error.

Maybe I've wrote the job wrong? If so, what is the correct way to fail a job and be able to capture it in test?

all my jobs are run in sync mode. not redis. so no supervisor or anything like that.

0 likes
2 replies
martinbean's avatar

@roniwashere You simply dispatch the job.

Create an access token with an expires_at value in the past, and then dispatch the job asynchronously but set an expectation for the exception:

AccessToken::factory()->create([
    'expires_at' => Carbon::yesterday(),
]);

$this->expectException(YourException::class);

YourJob::dispatchSync();

It’s been a while since I‘ve worked with Lumen, so you may need to change the syntax for the factory and dispatching of the job, but that’s the general gist of it.

RoniWasHere's avatar

@martinbean well, it says Failed asserting that exception of type "App\Exceptions\MyException" is thrown.

I think because the exception is passed to the fail method and not actually thrown.

Please or to participate in this conversation.