Laravel 8 通知模擬

2021-07-26 09:35 更新

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

<?php

namespace Tests\Feature;

use App\Notifications\OrderShipped;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Notifications\AnonymousNotifiable;
use Illuminate\Support\Facades\Notification;
use Tests\TestCase;

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

        // 斷言沒有發(fā)送通知...
        Notification::assertNothingSent();

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

        // 斷言已發(fā)送特定類型的通知以滿足給定的真實(shí)性測(cè)試...
        Notification::assertSentTo(
            $user,
            function (OrderShipped $notification, $channels) use ($order) {
                return $notification->order->id === $order->id;
            }
        );

        // 斷言向給定用戶發(fā)送了通知...
        Notification::assertSentTo(
            [$user], OrderShipped::class
        );

        // 斷言沒有發(fā)送通知...
        Notification::assertNotSentTo(
            [$user], AnotherNotification::class
        );

        // 斷言通過(guò) Notification::route() 方法發(fā)送通知...
        Notification::assertSentTo(
            new AnonymousNotifiable, OrderShipped::class
        );

        // 斷言通過(guò) Notification :: route() 方法向給定用戶發(fā)送了通知...
        Notification::assertSentTo(
            new AnonymousNotifiable,
            OrderShipped::class,
            function ($notification, $channels, $notifiable) use ($user) {
                return $notifiable->routes['mail'] === $user->email;
            }
        );
    }
} 


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

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)