Test Job Failures Precisely with Laravel's assertFailedWith Method
Last updated on by Harris Raftopoulos

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.