1 回答
TA贡献1871条经验 获得超13个赞
看起来MailChannel发送通知电子邮件的驱动程序没有使用Mail外观,这意味着Mail::fake不会影响它。相反,它直接调用该send方法,该方法又调用(邮件驱动程序)。MailablesendMailer
您可以将Mailable实例替换为MailFake(这是Mail::fake使用的)的实例,但它看起来MailFake不适合当$view是一个数组(这是MailChannel传递给 的内容Mailable)的情况。
幸运的是,Laravel 源代码包含一个示例,说明他们如何测试在SendingMailNotificationsTest. 他们模拟MailerandMarkdown实例并检查传递的参数。你可以做类似的事情:
use Mockery as m;
use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Mail\Markdown;
use Illuminate\Mail\Message;
class ContactFormTest extends TestCase
{
protected function tearDown(): void
{
parent::tearDown();
m::close();
}
protected function setUp(): void
{
parent::setUp();
$this->mailer = m::mock(Mailer::class);
$this->markdown = m::mock(Markdown::class);
$this->instance(Mailer::class, $this->mailer);
$this->instance(Mailer::class, $this->markdown);
}
public function a_mail_is_send_when_the_contact_form_is_used()
{
$this->withExceptionHandling();
$user = factory(User::class)->create();
$this->markdown->shouldReceive('render')->once()->andReturn('htmlContent');
$this->markdown->shouldReceive('renderText')->once()->andReturn('textContent');
$data = [
'name' => 'John Doe',
'email' => 'email@email.com',
'message' => 'This is a test message'
];
$notification = new ContactRequestNotification($data);
$this->mailer->shouldReceive('send')->once()->with(
['html' => 'htmlContent', 'text' => 'textContent'],
array_merge($notification->toMail($user)->toArray(), [
'__laravel_notification' => get_class($notification),
'__laravel_notification_queued' => false,
]),
m::on(function ($closure) {
$message = m::mock(Message::class);
$message->shouldReceive('to')->once()->with([$user->email]);
$closure($message);
return true;
})
);
$response = $this->post('/contact', $data);
$response->assertStatus(200);
}
}
就个人而言,我现在宁愿只toMail对类上的方法进行单元测试,ContactRequestNotification因为我认为上面的方法不是很漂亮。
- 1 回答
- 0 关注
- 242 浏览
添加回答
举报
