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...