Метод fake
Метод fake класса Notification подменяет реальную службу уведомлений на фальшивую. Это полезно при тестировании, чтобы избежать реальной отправки уведомлений. Метод принимает массив классов уведомлений, которые необходимо фейковать. Если массив не передан, фейкуются все уведомления.
Синтаксис
<?php
use Illuminate\Support\Facades\Notification;
Notification::fake();
Notification::fake([OrderShipped::class, InvoicePaid::class]);
?>
Пример
Фейкуем все уведомления и проверяем, что OrderShipped было отправлено пользователю:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Models\User;
use App\Models\Order;
use App\Notifications\OrderShipped;
use Illuminate\Support\Facades\Notification;
class OrderTest extends TestCase
{
public function test_order_shipped_sends_notification()
{
Notification::fake();
$user = User::factory()->create();
$order = Order::factory()->create(['user_id' => $user->id]);
$user->notify(new OrderShipped($order));
Notification::assertSentTo(
$user,
OrderShipped::class
);
}
}
?>
Результат выполнения кода:
"Test passed: Notification was sent"
Пример
Фейкуем только конкретные уведомления и отправляем несколько типов:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Models\User;
use App\Notifications\WelcomeEmail;
use App\Notifications\InvoicePaid;
use Illuminate\Support\Facades\Notification;
class UserTest extends TestCase
{
public function test_user_receives_multiple_notifications()
{
Notification::fake([WelcomeEmail::class]);
$user = User::factory()->create();
$user->notify(new WelcomeEmail());
$user->notify(new InvoicePaid());
Notification::assertSentTo(
$user,
WelcomeEmail::class
);
Notification::assertNotSentTo(
$user,
InvoicePaid::class
);
}
}
?>
Результат выполнения кода:
"Test passed: WelcomeEmail sent, InvoicePaid not sent"
Пример
Проверяем, что уведомление отправлено через определенный канал:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Models\User;
use App\Models\Order;
use App\Notifications\OrderShipped;
use Illuminate\Support\Facades\Notification;
class OrderTest extends TestCase
{
public function test_notification_sent_via_mail()
{
Notification::fake();
$user = User::factory()->create();
$order = Order::factory()->create(['user_id' => $user->id]);
$user->notify(new OrderShipped($order));
Notification::assertSentTo(
$user,
OrderShipped::class,
function ($notification, $channels) use ($order) {
return $notification->order->id === $order->id
&& in_array('mail', $channels);
}
);
}
}
?>
Результат выполнения кода:
"Test passed: Notification sent via mail channel"
Смотрите также
-
класс
Notification,
который предоставляет методы для работы с уведомлениями -
метод
assertSentTo,
который проверяет отправку уведомления получателю -
класс
Mail,
который используется для тестирования почтовых отправлений -
класс
Queue,
который используется для тестирования очередей