Laravel job attempts / pogingen testen in feature testen

published 27-01-2025
Hierbij een artikel hoe je job attempts kan testen in een Laravel feature test. Ik heb een job die een betaling doet. Als dit niet lukt moet de klant een mailtje krijgen. Alleen wil je dit niet meteen al na de eerste mislukte poging, maar zeg bij de 3e mislukte poging.
Job
Een voorbeeld van een job
<?php
class TestJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $user;
public function __construct()
{
}
public function handle(): void
{
// $this->user = get the user..
$this->notifyCustomer();
abort(404);
}
private function notifyCustomer():void
{
if ($this->attempts() === 3) {
Mail::to($this->user)
->send(new PaymentFailedMail());
}
}
}
Feature test
<?php
test('expect a notification to a customer if a payment failed', function () {
Mail::fake();
try {
$job = new TestJob();
$job->handle();
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
// Handle other exceptions here
}
Mail::assertQueued(PaymentFailedMail::class);
});
Deze test zal nu niet slagen, omdat erbij de 3e poging het mailtje er pas uit gaat.
Mock attemt
Hieronder de aangepaste test waarin we aangeven dat we de attempts willen mocken. De test zal nu wel slagen.
<?php
test('expect a notification to a customer if a payment failed', function () {
Mail::fake();
$mockJob = $this->mock(
RedisJob::class,
function (MockInterface $mock) {
$mock->shouldReceive('attempts')->once()
->andReturn(3);
}
);
try {
$job = new TestJob();
$job->setJob($mockJob);
$job->handle();
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
// Handle other exceptions here
}
Mail::assertQueued(PaymentFailedMail::class);
});