我如何测试一个Laravel作业在测试中派出另一个作业?

问题描述 投票:0回答:1

我有以下Laravel Worker:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;

use App\Lobs\AnotherJob;

class MyWorker implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;

    public function handle(): void
    {
       AnotherJob::dispatch();
    }
}

而且我想对我的工作分配AnotherJob进行单元测试:

namespace Tests;

use Illuminate\Foundation\Testing\TestCase;

class TestMyWorker extends TestCase
{
  public function testDispachesAnotherJob()
  {
    MyWorker::dispatchNow();
    //Assert that AnotherJob is dispatched
  }
}

你知道我怎么能冒充AnotherJob::dispatch()的名字吗?

php laravel phpunit assert jobs
1个回答
0
投票

Laravel具有queue mocks/fakes来处理。试试这个:

namespace Tests;

use Illuminate\Foundation\Testing\TestCase;
use Illuminate\Support\Facades\Queue;
use App\Jobs\MyWorker;
use App\Jobs\AnotherJob;

class TestMyWorker extends TestCase
{
  public function testDispachesAnotherJob()
  {
    Queue::fake();
    MyWorker::dispatchNow();
    Queue::assertPushed(MyWorker::class);
    Queue::assertPushed(AnotherJob::class);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.