阅读(1645) (11)

Laravel 8 通知模拟

2021-07-08 16:55:52 更新

你可以使用 Notification Facade 的 fake 方法来模拟通知的发送,测试时并不会真的发出通知。然后你可以断言 notifications 发送给了用户,甚至可以检查他们收到的内容。使用 fakes 时,断言一般放在测试代码后面:

<?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();

        // 断言没有发送通知...
        Notification::assertNothingSent();

        // 执行订单发送...

        // 断言已发送特定类型的通知以满足给定的真实性测试...
        Notification::assertSentTo(
            $user,
            function (OrderShipped $notification, $channels) use ($order) {
                return $notification->order->id === $order->id;
            }
        );

        // 断言向给定用户发送了通知...
        Notification::assertSentTo(
            [$user], OrderShipped::class
        );

        // 断言没有发送通知...
        Notification::assertNotSentTo(
            [$user], AnotherNotification::class
        );

        // 断言通过 Notification::route() 方法发送通知...
        Notification::assertSentTo(
            new AnonymousNotifiable, OrderShipped::class
        );

        // 断言通过 Notification :: route() 方法向给定用户发送了通知...
        Notification::assertSentTo(
            new AnonymousNotifiable,
            OrderShipped::class,
            function ($notification, $channels, $notifiable) use ($user) {
                return $notifiable->routes['mail'] === $user->email;
            }
        );
    }
}