单元测试Laravel密码重置电子邮件 - mailable没有排队

时间:2018-05-17 03:44:52

标签: php laravel unit-testing laravel-5 phpunit

我正在使用Laravel附带的auth。我正在测试您放入电子邮件的页面,当您点击提交按钮时,密码重置电子邮件将发送到您的电子邮箱。

我手动执行密码重置电子邮件。但我创建了这个测试,以确保密码重置电子邮件已发送,但它无法正常工作。

  

有1次失败:

     

1)   预期的[Illuminate \ Foundation \ Auth \ ResetPassword] mailable没有排队。   声明false为真的失败。

我正在关注此代码:

https://github.com/JeffreyWay/council/blob/master/tests/Feature/Auth/RegisterUserTest.php

<?php

namespace Tests\Controllers\Unit;

use Tests\TestCase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ResetPasswordEmailTest extends TestCase
{

    use RefreshDatabase;


    public function setUp()
    {
        parent::setUp();

        Mail::fake();
    }


    /** @test */
    public function does_send_password_reset_email()
    {
        $user = factory('App\User')->create();

        $this->post(route('password.email'), ['email' => $user->email])

        Mail::assertQueued(ResetPassword::class);
    }

}

1 个答案:

答案 0 :(得分:1)

您收到此错误,因为密码重置电子邮件是Notification而不是Mailable。请注意,还必须保存伪造的用户,以便密码重置代码可以在数据库中查找它。对我有用的是这样的:

<?php

namespace Tests\Controllers\Unit;

use Tests\TestCase;
use Illuminate\Support\Facades\Notification;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ResetPasswordEmailTest extends TestCase
{
    use RefreshDatabase;

    public function setUp()
    {
        parent::setUp();
        Notification::fake();
    }

    /** @test */
    public function does_send_password_reset_email()
    {
        $user = factory('App\User')->create();
        $user->save();
        $this->post(route('password.email'), ['email' => $user->email])
        Notification::assertSentTo($user, ResetPassword::class);
    }
}

您还可以使用以下方式检查电子邮件内容:

Notification::assertSentTo(
    $user,
    ResetPassword::class, 
    function($notification, $channels) use ($user) {
        $mail = $notification->toMail($user)->build();
        $expected_subject = "Here's your password reset";
        return $mail->subject === $expected_sub;
    }
);