测试中未分配作业

Saú*_*ano 5 php testing phpunit laravel

我正在使用 Laravel 8 和 Laravel Sail。

我正在尝试测试一封从工作中发送但无论我做什么都没有发送的电子邮件。这是我的代码

Bus::fake();
Mail::fake();
TheProductDoesNotExists::dispatch($this->channel, $document['product'], $document['name']);
Event::assertDispatched(TheProductDoesNotExists::class);
Mail::assertSent(ProductMissing::class);
Run Code Online (Sandbox Code Playgroud)

我得到

The expected [App\Mail\ProductMissing] mailable was not sent.
  Failed asserting that false is true.
Run Code Online (Sandbox Code Playgroud)

在作业内部,我什至在处理方法中有一个记录器,但没有记录任何内容

public function handle()
    {
        logger('from the job');
        $alertTo = 'test@test';
        Mail::to($alertTo)->send(
            new ProductMissing($this->product, $this->orderName)
        );
    }
Run Code Online (Sandbox Code Playgroud)

没事了。任何帮助将非常感激!谢谢

Kev*_*Bui 4

当您编写Queue::fake()Bus::fake()时,框架将用简单数组替换真正的队列(redis、数据库...)。所有作业都将存储在该数组中,并且不会被执行。该数组用于后续断言。所以在你的代码中:

Bus::fake();
Mail::fake();
TheProductDoesNotExists::dispatch($this->channel, $document['product'], $document['name']);
Event::assertDispatched(TheProductDoesNotExists::class);
Mail::assertSent(ProductMissing::class);
Run Code Online (Sandbox Code Playgroud)

因为TheProductDoesNotExists甚至没有执行,所以没有捕获电子邮件并且最后一行失败。

您只能测试这两者之一。

Bus::fake();
TheProductDoesNotExists::dispatch($this->channel, $document['product'], $document['name']);
Bus::assertDispatched(TheProductDoesNotExists::class);
Run Code Online (Sandbox Code Playgroud)

或者:

Mail::fake()
TheProductDoesNotExists::dispatchNow($this->channel, $document['product'], $document['name']);
Mail::assertSent(ProductMissing::class);
Run Code Online (Sandbox Code Playgroud)

不是同时两者。

为了更好地理解,我建议阅读Illuminate\Support\Testing\Fakes\QueueFakeLaravel 源代码中的类。