• Reading time ~ 1 min
  • 05.06.2025

Laravel introduces the assertFailedWith method for more precise testing of queued job failures, enabling developers to verify exactly how and why jobs fail rather than just confirming failure occurred.

The assertFailedWith method supports multiple assertion types for comprehensive job failure testing:

use App\Jobs\ProcessDocument;
use App\Exceptions\ProcessingException;
$job = (new ProcessDocument)->withFakeQueueInteractions();
// Test with message
$job->assertFailedWith('processing failed');
// Test with exception class
$job->assertFailedWith(ProcessingException::class);
// Test with exception instance
$job->assertFailedWith(new ProcessingException);
// Test with specific message
$job->assertFailedWith(new ProcessingException(message: 'invalid format'));
// Test with message and code
$job->assertFailedWith(new ProcessingException(message: 'timeout error', code: 408));

It could also be used for integration testing with external services:

class ExternalServiceJobTest extends TestCase
{
    public function test_api_sync_handles_rate_limiting()
    {
        Http::fake(['*' => Http::response([], 429)]);
        $job = new SyncExternalDataJob($apiEndpoint)
            ->withFakeQueueInteractions();
        $job->handle();
        $job->assertFailedWith(
            new RateLimitException('API rate limit exceeded', 429)
        );
    }
    public function test_webhook_delivery_handles_invalid_endpoint()
    {
        $job = new DeliverWebhookJob('invalid-url', $payload)
            ->withFakeQueueInteractions();
        $job->handle();
        $job->assertFailedWith(
            new InvalidEndpointException('Invalid webhook URL format')
        );
    }
}

The assertFailedWith method enables comprehensive job failure testing by verifying specific failure conditions, making test suites more reliable and helping developers ensure proper error handling in their queue workers.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297

We shoot down "Shahed" drones every day. Each one downed means lives saved. But we need mobility: a van or a trailer. Every donation = another night under protection.

🚐 Van fundraiser for my unit, 1020 regiment 🎯 Goal: 500,000 ₴
🔗 Donation link 💳 4441 1111 2546 4663