Courses

Testing in Laravel 11: Advanced Level

Testing Jobs in Queue

Summary of this lesson:
- Learn how to test Laravel job classes
- Manually call job handle() method
- Verify job performs expected actions
- Check database changes after job execution
- Understand job testing techniques

In this lesson, I will show you how to test Laravel Job classes.


Job Example

Imagine you have ProductPublishJob and want to dispatch it from an Artisan command, Controller, or anywhere else.

The Job is straightforward: it finds the product by ID and publishes it by setting published_at.

app/Jobs/ProductPublishJob.php

use App\Models\Product;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
 
class ProductPublishJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
 
public function __construct(public int $productId)
{}
 
public function handle(): void
{
$product = Product::find($this->productId);
 
if ($product && ! $product->published_at) {
$product->update(['published_at' => now()]);
}
}
}

The Job itself could be put into a queue, but you don't need to test it. You need to test that the Job changes the data successfully.


Test

So, in the test, we first check...

The full lesson is only for Premium Members.
Want to access all 31 lessons of this course? (74 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord