未发送预期的 [App\Mail\WelcomeEmail] 邮件。无法断言 false 为 true

The expected [App\Mail\WelcomeEmail] mailable was not sent. Failed asserting that false is true

我哪里弄错了?打击代码不适用于测试。 找到了用户。没有像user null这样的问题。

错误信息为:

The expected [App\Mail\WelcomeEmail] mailable was not sent. Failed asserting that false is true.

   at vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/MailFake.php:64
  60|         }
  61| 
  62|         PHPUnit::assertTrue(
  63|             $this->sent($mailable, $callback)->count() > 0,
> 64|             $message
  65|         );
  66|     }
  67| 

测试class

class MailTest extends TestCase
{
    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function testWelcomeMail()
    {
        $this->withoutExceptionHandling();
        Mail::fake();

        Mail::assertSent(WelcomeEmail::class);
    }
}

邮件class

class WelcomeEmail extends Mailable
{
 use Queueable, SerializesModels;

 public $data;

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

 public function build()
 {
    $user = User::find(3425);

    $address = 'myjourney@asdasd.com';
    $subject = __('email.welcome_to_journey');
    $name = __('email.my_journey');

    if ($user != NULL) {
        \App::setLocale($user->lang);
        $user->is_welcome_email_sent = 1;
        $user->save();

    }

    return $this->view('email.user_welcome', ['user' => $user])
        ->from($address, $name)
        // ->cc($address, $name)
        // ->bcc($address, $name)
        ->replyTo($address, $name)
        ->subject($subject);
 }
}

我可以处理其他测试文件,如登录、注册等,但邮寄不行。

是否真的有 id 为 3425 的用户?

$user = User::find(3425);

您的代码可能会在这里中断,因为我们无法从空对象中检索 lang。此行可能应该被删除,因为它已经在您检查用户是否存在的下方的一行中使用。

\App::setLocale($user->lang); 

您的电子邮件模板似乎也使用了 $user 中的数据,因为用户对象已传递给模板。如果您希望用户存在,这也可能会中断。

您没有将电子邮件与其他凭据一起发送。你的函数应该是这样的

public function testWelcomeMail()
{
    $this->withoutExceptionHandling();
    Mail::fake();
    Mail::to('<email_address>')->send(new WelcomeEmail(['user' => <some_number>]));
    Mail::assertSent(WelcomeEmail::class);
}