在Laravel中测试从Notification发送的邮件,可以按照以下步骤进行:
Illuminate\Notifications\Notification
的Notification类,该类负责定义要发送的邮件内容和配置。via()
方法定义邮件通知渠道为mail
。toMail()
方法定义邮件的主题、内容和其他相关信息。Notification::fake()
方法来模拟发送邮件,然后调用要测试的代码,触发Notification的发送。最后,使用Notification::assertSentTo()
方法来断言邮件是否被发送到了指定的收件人。以下是一个示例代码:
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Notification as NotificationFacade;
use Tests\TestCase;
class EmailNotificationTest extends TestCase
{
public function testEmailNotification()
{
NotificationFacade::fake();
$user = User::find(1);
$user->notify(new WelcomeNotification());
NotificationFacade::assertSentTo(
$user,
WelcomeNotification::class,
function ($notification, $channels, $notifiable) {
return in_array('mail', $channels) &&
$notification->toMail($notifiable)->subject == 'Welcome to our website';
}
);
}
}
class WelcomeNotification extends Notification
{
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Welcome to our website')
->line('Thank you for signing up!')
->action('Visit Website', url('/'));
}
}
在上述示例中,我们首先使用Notification::fake()
方法来模拟发送邮件。然后,创建一个用户实例,并调用notify()
方法来发送WelcomeNotification邮件。最后,使用Notification::assertSentTo()
方法来断言邮件是否被发送到了指定的收件人,并验证邮件的主题是否正确。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)
领取专属 10元无门槛券
手把手带您无忧上云