In this blog post, we'll explore how to test Laravel jobs, specifically focusing on asserting that a batch of jobs has been dispatched and testing that a then method is called when all the batched jobs are completed. // BatchCompletedJob.php get('batch'); Bus::assertBatched(function (PendingBatch $batch) { $this->assertCount(2, $batch->jobs); $this->assertSame('first', $batch->jobs->name); $this->assertSame('second', $batch->jobs->name); return true; }); } public function asssert_then_method_is_called(): void { Bus::fake(); $this->get('batch'); // assert, then the method is called and executed Bus::batched(function (PendingBatch $batch) { // get then callback [$thenCallback] = $batch->thenCallbacks(); // excecute it $thenCallback->getClosure()->call($this, $this); // make desired assertions db record is saved, event or job is dispatched Bus::assertDispatched(BatchCompletedJob::class, 1); return true; }); }} In the first test method, assert_batch_of_jobs_was_dispatched, we want to make sure that the batch of jobs is dispatched correctly.

Just as we've explored testing the then method, the same principles apply when you want to test the finally and catch methods in Laravel batch jobs.

Access the finally callback with finallyCallbacks() method within your batched job, execute it, and make the necessary assertions.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners