I have the following Laravel Controller:
namespace App\Controller;
use App\Jobs\MyJob;
class JobDispatchControler
{
public function callJob(Request $request)
{
MyJob::dispatch();
}
}
The controller above has the following route:
Route::get('/job',"\App\Controller\JobDispatchControler@callJob");
And I want to test whether I a call to the /job
will dispatch the MyJob
job:
namespace Test\App\MyJob;
use Illuminate\Foundation\Testing\TestCase;
use Illuminate\Support\Facades\Queue;
use App\Jobs\MyJob;
class TestDispatchJob extends TestCase
{
public function testJobDispatch()
{
Queue::fake();
self::get("/job");
Queue::assertPushed(MyJob::class);
}
}
But Once I run via phpunit the test I get the following error:
Time: 4.63 seconds, Memory: 34.00 MB
There was 1 failure:
1) Test\App\MyJob::testJobDispatch
The expected [App\Jobs\MyJob] job was not pushed.
/var/www/html/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/QueueFake.php:33
/var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:237
/var/www/html/tests/App/MyJob/TestDispatchJob.php:26
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
Do you know why I fail to assert that my job jas not been dispatched?
Edit 1
According to this article I changed my test into:
namespace Test\App\MyJob;
use Illuminate\Foundation\Testing\TestCase;
use Illuminate\Support\Facades\Bus;
use App\Jobs\MyJob;
class TestDispatchJob extends TestCase
{
public function testJobDispatch()
{
Bus::fake();
self::get("/job");
Bus::assertDispatched(MyJob::class);
}
}
And still get the following error:
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
Time: 4.63 seconds, Memory: 34.00 MB
There was 1 failure:
1) Test\App\MyJob::testJobDispatch
The expected [App\Jobs\MyJob] job was not dispatched.
/var/www/html/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/BusFake.php:32
/var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:237
/var/www/html/tests/App/MyJob/TestDispatchJob.php:26
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
But once instead of triggering the get
method arbitary dispach the job seems to work ok:
namespace Test\App\MyJob;
use Illuminate\Foundation\Testing\TestCase;
use Illuminate\Support\Facades\Bus;
use App\Jobs\MyJob;
class TestDispatchJob extends TestCase
{
public function testJobDispatch()
{
Bus::fake();
MyJob::dispatch();
Bus::assertDispatched(MyJob::class);
}
}