php - 单元测试 Laravel 密码重置电子邮件 - 可邮寄未排队

标签 php laravel unit-testing laravel-5 phpunit

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

密码重设电子邮件是在我手动执行时发送的。但是我创建了这个测试以确保密码重置电子邮件已发送,但它不起作用。

There was 1 failure:

1) The expected [Illuminate\Foundation\Auth\ResetPassword] mailable was not queued. Failed asserting that false is true.

我正在遵循这段代码:

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);
    }

}

最佳答案

您收到该错误是因为密码重置电子邮件是 Notification 而不是 Mailable。对我有用的是这样的:

<?php

namespace Tests\Controllers\Unit;

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

class ResetPasswordEmailTest extends TestCase
{
    use RefreshDatabase;

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

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

您还可以使用回调作为第三个参数来验证电子邮件的内容。回调接收通知和 channel 数组,并应返回 true 或 false 以通过或失败断言。例如:

$expected_subject = "Here's your password reset";
Notification::assertSentTo(
    $user,
    ResetPassword::class, 
    fn ($n, $c) => $n->toMail($user)->build()->subject === $expected_sub;
);

关于php - 单元测试 Laravel 密码重置电子邮件 - 可邮寄未排队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50383016/

相关文章:

javascript - 将 php 变量传递给 joomla 中的 javascript

javascript - Laravel - 消息 Toastr,错误或无效输入字段

使用 Auth::User 进行 Laravel 查询

c# - .net 中的单元和集成测试组织

安卓。如何从 Espresso 测试库中滑动 NavigationDrawer?

php - 找到所有的 <img> 标签,去掉 height 和 width 然后把去掉的值放在 <img> 标签的样式中

php - 避免在 Controller 上使用 Laravel facade

php - Laravel Homestead Mongo 安装导致 PHP 错误 undefined symbol : php_json_serializable_ce in Unknown on line 0

unit-testing - grails Grails单元测试中的应用程序访问

php - 在计算其他表中的行时更新行