РЕПЕТИТОР математика физика информатика
Для школьников и студентов. Подтягивание пробелов. ЦЭ, ЦТ, ОГЭ, ЕГЭ.
Идет набор на ЛЕТО. Жмите для подробностей:)
1257 of 1392 menu

Класс Notification

Класс Notification из пространства имён Illuminate\Support\Facades предназначен для тестирования уведомлений в Laravel. Он позволяет создать фейковую реализацию уведомлений, которая перехватывает все отправляемые уведомления и предоставляет методы для проверки, были ли они отправлены, и каким получателям. Основное применение класса - это написание тестов, где нужно убедиться, что уведомление отправлено при определённых условиях, без реальной отправки.

Основные методы класса: fake - создаёт фейковую реализацию, assertSentTo - проверяет, что уведомление отправлено указанному получателю, assertNotSentTo - проверяет, что уведомление не отправлено, и другие вспомогательные методы для проверки количества отправленных уведомлений и их содержимого.

Синтаксис

<?php use Illuminate\Support\Facades\Notification; // Создание фейка Notification::fake(); // Проверка отправки уведомления Notification::assertSentTo( $notifiable, NotificationClass::class, function ($notification, $channels) { return $notification->message === 'abcde'; } ); ?>

Пример

Давайте протестируем отправку уведомления при регистрации нового пользователя:

<?php namespace Tests\Unit; use Tests\TestCase; use App\Models\User; use App\Notifications\WelcomeNotification; use Illuminate\Support\Facades\Notification; class UserTest extends TestCase { public function test_welcome_notification_sent_on_registration() { Notification::fake(); $user = User::factory()->create([ 'name' => 'John Doe', 'email' => 'john@example.com', ]); $user->sendWelcomeNotification(); Notification::assertSentTo( $user, WelcomeNotification::class ); } } ?>

Результат выполнения кода:

"Test passed: notification sent successfully"

Пример

Проверим, что уведомление отправлено через правильные каналы:

<?php namespace Tests\Unit; use Tests\TestCase; use App\Models\User; use App\Notifications\OrderShippedNotification; use Illuminate\Support\Facades\Notification; use Illuminate\Notifications\Channels\MailChannel; use Illuminate\Notifications\Channels\DatabaseChannel; class NotificationTest extends TestCase { public function test_notification_sent_via_mail_and_database() { Notification::fake(); $user = User::factory()->create(); $user->notify(new OrderShippedNotification()); Notification::assertSentTo( $user, OrderShippedNotification::class, function ($notification, $channels) { return in_array('mail', $channels) && in_array('database', $channels); } ); } } ?>

Результат выполнения кода:

"Notification verified through mail and database channels"

Пример

Проверим, что уведомление не отправлено при определённом условии:

<?php namespace Tests\Unit; use Tests\TestCase; use App\Models\User; use App\Models\Order; use App\Notifications\OrderShippedNotification; use Illuminate\Support\Facades\Notification; class OrderTest extends TestCase { public function test_notification_not_sent_for_draft_orders() { Notification::fake(); $user = User::factory()->create(); $order = Order::factory()->create([ 'status' => 'draft', 'user_id' => $user->id, ]); $order->processShipping(); Notification::assertNotSentTo( $user, OrderShippedNotification::class ); } } ?>

Результат выполнения кода:

"Test passed: notification not sent as expected"

Пример

Проверим, сколько раз было отправлено уведомление нескольким получателям:

<?php namespace Tests\Unit; use Tests\TestCase; use App\Models\User; use App\Notifications\SystemAlertNotification; use Illuminate\Support\Facades\Notification; class BroadcastTest extends TestCase { public function test_notification_sent_to_multiple_users() { Notification::fake(); $users = User::factory()->count(3)->create(); $admins = User::factory()->count(2)->create([ 'is_admin' => true, ]); $allUsers = $users->merge($admins); Notification::send($allUsers, new SystemAlertNotification('System update')); Notification::assertSentTo( $allUsers, SystemAlertNotification::class ); Notification::assertSentToTimes( $allUsers, SystemAlertNotification::class, 5 ); } } ?>

Результат выполнения кода:

"Notifications sent 5 times"

Смотрите также

  • метод fake,
    который создаёт фейковую реализацию уведомлений для тестирования
  • метод assertSentTo,
    который проверяет отправку уведомления конкретному получателю
  • класс Event,
    который используется для тестирования событий
  • класс Mail,
    который используется для тестирования почтовых отправлений
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить