dongshi3605 2018-04-01 23:33
浏览 111

邮件::假Laravel单元测试不起作用,真正的控制器工作

I would like to test if RegistrationUser mailable in Laravel 5.6 can send to selected email address.

I created RegistrationUser class:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class RegistrationUser extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.registration.user');
    }
}

After that I created EmailTest class:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Mail\RegistrationUser;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class EmailTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
        Mail::fake();
        // Assert a message was sent to the given users...
        Mail::assertSent(RegistrationUser::class, function ($mail)  {
            return $mail->hasTo('test@o2.pl');
        });
    }
}

When I run PHPUnit I get this error:

PHPUnit 7.0.3 by Sebastian Bergmann and contributors.

F..                                                                 3 / 3 (100%)

Time: 143 ms, Memory: 18.00MB

There was 1 failure:

1) Tests\Feature\EmailTest::testExample
The expected [App\Mail\RegistrationUser] mailable was not sent.
Failed asserting that false is true.

/Users/mateusz/Sites/fifa/backend/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/MailFake.php:41
/Users/mateusz/Sites/fifa/backend/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:221
/Users/mateusz/Sites/fifa/backend/tests/Feature/EmailTest.php:24

FAILURES!
Tests: 3, Assertions: 3, Failures: 1.

Sending an email with the actual controller works and delivers the email message.

I don't know why this test code reports a failure.

  • 写回答

1条回答 默认 最新

  • doubing3662 2018-12-24 02:52
    关注

    You need to build the message you're sending.

    Add the following inside your assertSent

    $mail->build();
    

    So that it is now this:

    Mail::assertSent(RegistrationUser::class, function ($mail)  {
        $mail->build();
    
        return $mail->hasTo('test@example.com');
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗