【问题标题】:Job not being dispatched in test作业未在测试中分派
【发布时间】:2021-07-30 18:28:04
【问题描述】:

我正在使用 laravel 8 和 Laravel Sail。

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

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

我得到了

The expected [App\Mail\ProductMissing] mailable was not sent.
  Failed asserting that false is true.

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

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

什么都没有。任何帮助将非常感激!谢谢

【问题讨论】:

  • 您的问题是您混淆了事物,如果您伪造Event 总线,那么您将不会执行该事件...您在那里混合了 2 个测试,一个测试事件被分派,其他测试断言邮件已发送。

标签: php laravel testing phpunit


【解决方案1】:

当您编写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);

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

你只能测试这两个中的一个。

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

或者:

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

不能同时使用。

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

【讨论】:

  • 谢谢凯文!就是这样!
猜你喜欢
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 2020-12-03
  • 2023-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多