Laravel 8 郵件模擬

2021-07-26 09:35 更新

你可以是用 Mail Facade 的 fake 方法來模擬郵件發(fā)送,測(cè)試時(shí)不會(huì)真的發(fā)送郵件,然后你可以斷言 mailables 發(fā)送給了用戶,甚至可以檢查他們收到的內(nèi)容。使用 fakes 時(shí),斷言一般放在測(cè)試代碼的后面:

<?php

namespace Tests\Feature;

use App\Mail\OrderShipped;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function testOrderShipping()
    {
        Mail::fake();

        // 斷言沒有發(fā)送任何郵件...
        Mail::assertNothingSent();

        // 執(zhí)行訂單發(fā)送...

        // 斷言已派發(fā)特定類型的郵件,以滿足給定的真實(shí)性測(cè)試...
        Mail::assertSent(function (OrderShipped $mail) use ($order) {
            return $mail->order->id === $order->id;
        });

        // 斷言一條發(fā)送給用戶的消息...
        Mail::assertSent(OrderShipped::class, function ($mail) use ($user) {
            return $mail->hasTo($user->email) &&
                   $mail->hasCc('...') &&
                   $mail->hasBcc('...');
        });

        // 斷言郵件被發(fā)送兩次...
        Mail::assertSent(OrderShipped::class, 2);

        // 斷言沒有發(fā)送郵件...
        Mail::assertNotSent(AnotherMailable::class);
    }
} 

如果你用后臺(tái)任務(wù)執(zhí)行郵件發(fā)送隊(duì)列,你應(yīng)該是用 assertQueued 代替 assertSent

Mail::assertQueued(...);
Mail::assertNotQueued(...); 


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)