How to test Laravel 5 jobs?
Well, to test the logic inside handle
method you just need to instantiate the job class & invoke the handle
method.
public function testJobsEvents(){ $job = new \App\Jobs\YourJob; $job->handle(); // Assert the side effect of your job...}
Remember, a job is just a class after all.
Laravel version ^5 || ^7
Synchronous Dispatching
If you would like to dispatch a job immediately (synchronously), you may use the dispatchNow method. When using this method, the job will not be queued and will be run immediately within the current process:
Job::dispatchNow()
Laravel 8 update
<?phpnamespace Tests\Feature;use App\Jobs\ShipOrder;use Illuminate\Foundation\Testing\RefreshDatabase;use Illuminate\Foundation\Testing\WithoutMiddleware;use Illuminate\Support\Facades\Bus;use Tests\TestCase;class ExampleTest extends TestCase{ public function test_orders_can_be_shipped() { Bus::fake(); // Perform order shipping... // Assert that a job was dispatched... Bus::assertDispatched(ShipOrder::class); // Assert a job was not dispatched... Bus::assertNotDispatched(AnotherJob::class); }}