通过laravel文档,您使用notificationCreateType
导入Mail::fake()
来测试测试中的行为但是,当我模拟邮件时,我的测试失败,如果我使用ruby gem从控制器运行流程Illuminate\Support\Facades\Mail
对于SMTP服务器,我可以看到在mailcatcher
这里是测试用例代码,我在未能理解出错之后尝试了两种不同的断言
mailcatcher
我在事件服务类
中声明了观察者<?php
namespace Tests\Unit;
use Tests\TestCase;
use App\Entities\Requester;
use App\Mail\RequesterRegistered;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
class RequesterRegisteredTest extends TestCase {
use RefreshDatabase;
public function setUp()
{
parent::setUp();
Mail::fake();
}
public function testRequesterCreationTriggersEmail(){
$expected = factory(Requester::class)->create();
//assert email was to the company employee
Mail::assertSent(RequesterRegistered::class, function ($mail) use ($expected) {
return $mail->requester()->email_id === $expected->email_id;
});
// Assert a message was sent to the given users...
Mail::assertSent(RequesterRegistered::class, function ($mail) use ($expected) {
return $mail->hasTo($expected->email_id);
});
}
}
并且观察者有一个调用此邮件程序的已创建方法
public function boot()
{
parent::boot();
Requester::observe(RequesterObserver::class);
}
这里是测试结果
public function created(Requester $requester)
{
Log::debug("Sending registration email to :" . $requester->email_id);
$message = (new RequesterRegistered($requester))->onQueue('import-mailer');
Mail::to($requester->email_id)->queue($message);
}
更不用说这个观察者的类似事件测试如果碰巧使用MacBook-Pro-3:ctd-bo anadi$ ./vendor/bin/phpunit --filter RequesterRegisteredTest
PHPUnit 6.4.3 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 7.72 seconds, Memory: 16.00MB
There was 1 failure:
1) Tests\Unit\RequesterRegisteredTest::testRequesterCreationTriggersEmail
The expected [App\Mail\RequesterRegistered] mailable was not sent.
Failed asserting that false is true.
/Users/anadi/Code/CTD/ctd-bo/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/MailFake.php:41
/Users/anadi/Code/CTD/ctd-bo/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:221
/Users/anadi/Code/CTD/ctd-bo/tests/Unit/RequesterRegisteredTest.php:29
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
我使用Event::fake()
作为队列连接来测试环境和本地开发。
答案 0 :(得分:1)
在测试中,请尝试:Mail::assertQueued( ... )
。
即使您将队列驱动程序设置为同步,邮件假邮件也会将您的邮件放入其队列中,因为您有:
Mail::to($requester->email_id)->queue($message);
而不是:
Mail::to($requester->email_id)->send($message);