Laravel Queue and Job Testing: Bus::fake(), Queue::fake(), and Testing Job Logic
Laravel's queue system has first-class testing support through Bus::fake() and Queue::fake(). This post covers both faking strategies, assertDispatched patterns, how to test job logic in isolation, failed job handling, and testing job middleware chains.
Queued jobs are one of the most common patterns in Laravel applications — and one of the most commonly under-tested. Teams often test that a job was dispatched, but not what happens when it runs. Or they test the job logic, but forget to test the middleware and retry behavior. This post covers the complete picture.
Bus::fake() vs Queue::fake()
Laravel gives you two faking strategies, and choosing the right one matters.
Bus::fake() intercepts job dispatches at the command bus level. Jobs are recorded but never actually executed. Use this to assert that specific jobs were dispatched with correct arguments.
Queue::fake() intercepts at the queue driver level. It also records jobs without executing them. The key difference is that Queue::fake() gives you access to raw queue operations and works better when you dispatch jobs via dispatch() helper or ->dispatch() methods.
In practice, Bus::fake() is more commonly used because its assertion API is richer:
use Illuminate\Support\Facades\Bus;
use App\Jobs\ProcessPayment;
use App\Jobs\SendInvoice;
it('dispatches payment job when order is placed', function () {
Bus::fake();
$user = User::factory()->create();
$order = Order::factory()->for($user)->create(['total' => 5999]);
post('/orders/' . $order->id . '/pay', ['payment_token' => 'tok_visa'])
->assertRedirect('/orders/' . $order->id . '/confirmation');
Bus::assertDispatched(ProcessPayment::class);
});assertDispatched Patterns
Bus::assertDispatched() can take just a class name, or a callback that inspects the job:
it('dispatches payment job with correct amount', function () {
Bus::fake();
$order = Order::factory()->create(['total' => 7500]);
app(OrderService::class)->processPayment($order, 'tok_visa');
Bus::assertDispatched(ProcessPayment::class, function (ProcessPayment $job) use ($order) {
return $job->order->id === $order->id
&& $job->amount === 7500
&& $job->currency === 'usd';
});
});
// Assert multiple jobs dispatched in sequence
it('dispatches processing pipeline for new order', function () {
Bus::fake();
$order = Order::factory()->create();
app(OrderService::class)->submit($order);
Bus::assertDispatchedTimes(ProcessPayment::class, 1);
Bus::assertDispatched(ReserveInventory::class);
Bus::assertDispatched(SendConfirmationEmail::class);
Bus::assertNotDispatched(RefundPayment::class);
});
// Assert dispatch count
Bus::assertDispatchedTimes(ProcessPayment::class, 3);
// Assert nothing was dispatched at all
Bus::assertNothingDispatched();For chained jobs, use assertChained():
it('chains jobs in correct order', function () {
Bus::fake();
$order = Order::factory()->create();
app(OrderFulfillmentService::class)->fulfill($order);
Bus::assertChained([
ProcessPayment::class,
ReserveInventory::class,
ArrangeShipping::class,
SendTrackingEmail::class,
]);
});Testing Job Logic Directly
Asserting dispatch is only half the story. You also need to test that the job does the right thing when it runs. Do this by instantiating the job and calling handle() directly:
use App\Jobs\ProcessPayment;
use App\Services\PaymentGateway;
use Illuminate\Support\Facades\Http;
it('processes payment and marks order as paid', function () {
Http::fake([
'api.stripe.com/*' => Http::response(['id' => 'ch_test', 'status' => 'succeeded']),
]);
$order = Order::factory()->create(['status' => 'pending', 'total' => 4999]);
$job = new ProcessPayment($order, 'tok_visa');
$job->handle(app(PaymentGateway::class));
expect($order->fresh()->status)->toBe('paid')
->and($order->fresh()->stripe_charge_id)->toBe('ch_test');
});
it('marks order as failed when payment is declined', function () {
Http::fake([
'api.stripe.com/*' => Http::response(['error' => ['message' => 'Card declined']], 402),
]);
$order = Order::factory()->create(['status' => 'pending']);
$job = new ProcessPayment($order, 'tok_declined');
expect(fn() => $job->handle(app(PaymentGateway::class)))
->toThrow(\App\Exceptions\PaymentFailedException::class);
expect($order->fresh()->status)->toBe('payment_failed');
});For jobs that inject dependencies through the handle() method, resolve them from the service container:
it('sends welcome email to new user', function () {
Mail::fake();
$user = User::factory()->create(['email_verified_at' => now()]);
$job = new SendWelcomeEmail($user);
app()->call([$job, 'handle']); // resolves handle() dependencies automatically
Mail::assertSent(WelcomeEmail::class, function ($mail) use ($user) {
return $mail->hasTo($user->email);
});
});Delayed and Scheduled Jobs
Test that jobs are dispatched with the correct delay:
it('schedules reminder email 24 hours after signup', function () {
Bus::fake();
$user = User::factory()->create();
app(OnboardingService::class)->start($user);
Bus::assertDispatched(SendOnboardingReminder::class, function ($job) {
return $job->delay->diffInHours(now()) >= 23
&& $job->delay->diffInHours(now()) <= 25;
});
});For jobs dispatched on specific queues:
it('dispatches video processing to high-priority queue', function () {
Queue::fake();
$video = Video::factory()->create();
app(VideoService::class)->processUpload($video);
Queue::assertPushedOn('high-priority', ProcessVideoJob::class);
});Failed Jobs
Testing failure handling is critical — a job that fails silently is worse than one that doesn't run at all.
Testing the failed() method:
// App/Jobs/ProcessPayment.php
class ProcessPayment implements ShouldQueue
{
public int $tries = 3;
public function handle(PaymentGateway $gateway): void
{
$result = $gateway->charge($this->order, $this->token);
if (!$result->successful()) {
throw new PaymentFailedException($result->errorMessage());
}
$this->order->markAsPaid($result->chargeId());
}
public function failed(Throwable $exception): void
{
$this->order->markAsPaymentFailed();
Notification::send(
$this->order->user,
new PaymentFailedNotification($this->order)
);
Log::error('Payment job failed', [
'order_id' => $this->order->id,
'error' => $exception->getMessage(),
]);
}
}Test the failed() method directly:
it('marks order as failed and notifies customer when job fails permanently', function () {
Notification::fake();
$order = Order::factory()->create(['status' => 'pending']);
$user = $order->user;
$job = new ProcessPayment($order, 'tok_declined');
$job->failed(new PaymentFailedException('Card declined'));
expect($order->fresh()->status)->toBe('payment_failed');
Notification::assertSentTo($user, PaymentFailedNotification::class, function ($notification) use ($order) {
return $notification->order->id === $order->id;
});
});Testing retry behavior:
it('retries up to 3 times on network error', function () {
$gateway = Mockery::mock(PaymentGateway::class);
$gateway->shouldReceive('charge')
->times(3)
->andThrow(new NetworkException('Timeout'));
$order = Order::factory()->create();
$job = new ProcessPayment($order, 'tok_visa');
$job->tries = 3;
// Simulate job runner retrying
$attempts = 0;
for ($i = 0; $i < $job->tries; $i++) {
try {
$job->handle($gateway);
} catch (NetworkException $e) {
$attempts++;
}
}
expect($attempts)->toBe(3);
});Job Batches
Laravel Batch allows dispatching multiple jobs as a unit and tracking completion. Test batch behavior:
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
it('creates batch for bulk email send', function () {
Bus::fake();
$users = User::factory()->count(50)->create();
app(BulkEmailService::class)->send($users, 'monthly-newsletter');
Bus::assertBatched(function (PendingBatch $batch) {
return $batch->name === 'monthly-newsletter'
&& count($batch->jobs) === 50;
});
});
it('marks campaign as complete when batch finishes', function () {
$campaign = Campaign::factory()->create(['status' => 'sending']);
// Simulate batch completion callback
$batch = Mockery::mock(Batch::class);
$batch->shouldReceive('cancelled')->andReturn(false);
$callback = new MarkCampaignComplete($campaign);
$callback($batch);
expect($campaign->fresh()->status)->toBe('sent')
->and($campaign->fresh()->sent_at)->not->toBeNull();
});Job Middleware
Job middleware lets you apply cross-cutting behavior to jobs. Test the middleware in isolation and with the job:
// App/Jobs/Middleware/RateLimitedByUser.php
class RateLimitedByUser
{
public function handle(object $job, callable $next): void
{
$key = 'job:' . $job->user->id . ':' . class_basename($job);
Redis::throttle($key)
->allow(5)
->every(60)
->then(fn() => $next($job), function () use ($job) {
$job->release(30);
});
}
}Test the middleware directly:
it('releases job back to queue when rate limit exceeded', function () {
$user = User::factory()->create();
// Fill rate limit
Redis::throttle("job:{$user->id}:SendNotification")
->allow(5)->every(60)
->then(fn() => null, fn() => null);
for ($i = 0; $i < 5; $i++) {
Redis::throttle("job:{$user->id}:SendNotification")
->allow(5)->every(60)
->then(fn() => null, fn() => null);
}
$job = Mockery::mock(SendNotification::class);
$job->user = $user;
$job->shouldReceive('release')->once()->with(30);
$middleware = new RateLimitedByUser();
$middleware->handle($job, fn() => null);
});Test that a job uses the correct middleware:
it('uses rate limiting middleware', function () {
$order = Order::factory()->create();
$job = new ProcessPayment($order, 'tok_visa');
$middleware = collect($job->middleware());
expect($middleware->map(fn($m) => class_basename($m)))
->toContain('RateLimitedByUser')
->toContain('WithoutOverlapping');
});Putting It Together: A Complete Job Test
uses(RefreshDatabase::class);
describe('ProcessPayment job', function () {
beforeEach(function () {
$this->order = Order::factory()->create(['status' => 'pending', 'total' => 9999]);
$this->job = new ProcessPayment($this->order, 'tok_visa');
});
it('charges correct amount and marks order paid', function () {
Http::fake([
'api.stripe.com/*' => Http::response(['id' => 'ch_success', 'status' => 'succeeded']),
]);
app()->call([$this->job, 'handle']);
expect($this->order->fresh())
->status->toBe('paid')
->stripe_charge_id->toBe('ch_success');
});
it('has correct retry configuration', function () {
expect($this->job->tries)->toBe(3)
->and($this->job->backoff())->toBe([60, 120, 300]);
});
it('handles payment failure gracefully', function () {
Notification::fake();
Http::fake([
'api.stripe.com/*' => Http::response(['error' => 'declined'], 402),
]);
expect(fn() => app()->call([$this->job, 'handle']))
->toThrow(PaymentFailedException::class);
$this->job->failed(new PaymentFailedException('declined'));
expect($this->order->fresh()->status)->toBe('payment_failed');
Notification::assertSentTo($this->order->user, PaymentFailedNotification::class);
});
it('is dispatched when order is submitted', function () {
Bus::fake();
post('/orders/' . $this->order->id . '/submit')
->assertOk();
Bus::assertDispatched(ProcessPayment::class, fn($job) =>
$job->order->id === $this->order->id
);
});
});The pattern to internalize: use Bus::fake() to assert dispatch in feature tests, and call handle() directly in unit tests that test the job's business logic. Testing both layers catches different classes of bugs — dispatch issues and logic issues — and keeps each test focused on one concern.