This question is a bit old but I just found it and had the same problem.
@martinbean bwrice wants to test
function () {
CreateOrderReport::dispatch();
}
and be sure it works correctly. It does not have anything to do with the framework.
@bwrice this is a bit hacky but is enough for what I'm doing. I hope it will help you too.
First, you will need a BatchFake class :
use Carbon\CarbonImmutable;
use Illuminate\Bus\Batch;
use Illuminate\Bus\UpdatedBatchJobCounts;
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\Str;
use Illuminate\Support\Testing\Fakes\BatchRepositoryFake;
use Illuminate\Support\Testing\Fakes\PendingBatchFake;
use Illuminate\Support\Testing\Fakes\QueueFake;
class BatchFake extends Batch
{
public static function make(PendingBatchFake $batch): BatchFake
{
return new self(
new QueueFake(Facade::getFacadeApplication()),
new BatchRepositoryFake(),
(string) Str::orderedUuid(),
$batch->name,
count($batch->jobs),
count($batch->jobs),
0,
[],
$batch->options,
CarbonImmutable::now(),
null,
null
);
}
public function fresh(): self
{
return $this;
}
public function incrementFailedJobs(string $jobId): UpdatedBatchJobCounts
{
return new UpdatedBatchJobCounts(0, 1);
}
}
Then, in your test, you can "simply" do something like this :
Bus::fake();
$this->executeSomeCodeStartingABatch();
Bus::assertBatched(function (PendingBatchFake $batch) {
// the job id is irrelevant here, put what you want
BatchFake::make($batch)->recordSuccessfulJob('job_id');
return true;
});
// here, the `->then()` and `->finally()` callbacks are executed
// and ready to be tested. for example :
Bus::assertDispatched(CreateOrderReport::class);
Using the same system, you can also test the ->catch() callbacks.
Bus::fake();
$this->executeSomeCodeStartingABatch();
Bus::assertBatched(function (PendingBatchFake $batch) {
// the job id is irrelevant here, put what you want
BatchFake::make($batch)->recordFailedJob('job_id', new Exception('Oups!'));
return true;
});
// here, the `->catch()` and `->finally()` callbacks are executed
// and ready to be tested. for example :
Bus::assertNotDispatched(CreateOrderReport::class);
Hope it will help !