在Laravel单元测试中,正在发送的通知电子邮件不起作用

时间:2019-01-17 16:19:26

标签: laravel unit-testing email laravel-mail laravel-notification

我正在开发Laravel应用程序。我正在做单元测试。但是在测试发送的电子邮件方面存在一些问题。

我的测试代码是这样的。

public function test_something()
{
    Mail::fake();

    //other test code

    Mail::assertSent(\App\Mail\ApplicationCreatedEmail::class, 1);
}

在实际执行中。我将通知作为电子邮件发送。该通知是在事件中发送的。

我有一个值得通知的模型。

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable,
    //other code
}

我在这样的事件中发送通知。

class ApplicationCreated
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $application;

    public function __construct($application)
    {
        $this->application = $application;
    }
}

然后我有一个此类事件的侦听器。

class ApplicationCreatedListener
{
    public function handle(ApplicationCreated $event)
    {
        $event->application->user->notify(
            new ApplicationCreatedNotification($event->application)
        );
    }
}

如您所见,在侦听器中,我正在发送通知(ApplicationCreatedNotification)。这是ApplicationCreatedNotification的定义。

class ApplicationCreatedNotification extends Notification
{
    use Queueable;
    public $application;


    public function __construct(Application $application)
    {
        $this->application = $application;
    }


    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return new ApplicationCreatedEmail($notifiable)->to($notifiable->email);
    }


    public function toArray($notifiable)
    {
        return [

        ];
    }
}

如您所见,通知以电子邮件(可邮寄)的形式发送。

这是我的可邮寄类(ApplicationCreatedEmail)。

class ApplicationCreatedEmail extends Mailable implements ShouldQueue
{
    use SerializesModels, Queueable;

    public $application;

    public function __construct($application)
    {
        $this->application= $application;

        $this->subject('Application created');
    }


    public function build()
    {

        return $this->markdown('emails.application_created', []);
    }
}

然后在代码中,我在控制器中触发这样的事件。

event(new ApplicationCreated($application));

如您所见,如果您返回测试,我将尝试测试是否正在发送电子邮件。但这失败了,因为未发送电子邮件。但是,相反,如果我测试通知是否以这种方式发送。

public function test_something()
{
    Notification::fake();
    //other code
    Notification::assertSentTo($application->user, ApplicationCreatedNotification::class);
}

有效。测试通知的工作原理。测试发送的电子邮件失败。但是,如果我测试正在发送的电子邮件,则也会触发电子邮件类,因为我使用dd()帮助器记录了变量。它甚至运行有任何错误的mailable构建功能。只是测试失败。可能的错误是什么?我该如何解决?

0 个答案:

没有答案
相关问题