2

我正在做一个 Laravel 项目。我正在为我的应用程序编写集成/功能测试。我现在正在编写一个测试,我需要断言传递给电子邮件通知的数据和传递给它的视图的数据。我找到了这个链接,https://medium.com/@vivekdhumal/how-to-test-mail-notifications-in-laravel-345528917494

这是我的通知类

class NotifyAdminForHelpCenterCreated extends Notification
{
    use Queueable;

    private $helpCenter;

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

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

    public function toMail($notifiable)
    {
        return (new MailMessage())
            ->subject("Help Center registration")
            ->markdown('mail.admin.helpcenter.created-admin', [
                'helpCenter' => $this->helpCenter,
                'user' => $notifiable
            ]);
    }
}

正如您在代码中看到的,我将数据传递给 mail.admin.helpcenter.created-admin 刀片视图。

这是我的测试方法。

/** @test */
public function myTest()
{
    $body = $this->requestBody();
    $this->actingAsSuperAdmin()
        ->post(route('admin.help-center.store'), $body)
        ->assertRedirect();

    $admin = User::where('email', $body['admin_email'])->first();
    $helpCenter = HelpCenter::first();

    Notification::assertSentTo(
        $admin,
        NotifyAdminForHelpCenterCreated::class,
        function ($notification, $channels) use ($admin, $helpCenter) {
            $mailData = $notification->toMail($admin)->toArray();
            //here I can do some assertions with the $mailData
            return true;
        }
    );
}

正如您在测试中看到的我的评论,我可以使用 $mailData 变量做一些断言。但这不包括传递给视图的数据。如何断言或获取传递给刀片视图/模板的数据或变量?

4

1 回答 1

1

正如您在此处看到的,类上有一个viewData属性,MailMessage其中包含传递给视图的所有数据,无需将通知转换为数组。

$notification->toMail($admin)->viewData

所以在你的情况下会是这样的:

/** @test */
public function myTest()
{
    $body = $this->requestBody();
    $this->actingAsSuperAdmin()
        ->post(route('admin.help-center.store'), $body)
        ->assertRedirect();

    $admin = User::where('email', $body['admin_email'])->first();
    $helpCenter = HelpCenter::first();

    Notification::assertSentTo(
        $admin,
        NotifyAdminForHelpCenterCreated::class,
        function ($notification, $channels) use ($admin, $helpCenter) {
            $viewData = $notification->toMail($admin)->viewData;

            return $admin->is($viewData['user']) && $helpCenter->is($viewData['helpCenter']);
        }
    );
}
于 2020-04-24T12:33:01.490 回答