0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Notification Fakeを使って通知が送られたかどうかのテストを実装する

Posted at

環境

Laravel9
PHP8

やりたいこと

PHP UnitテストでメールやSMSなどの通知が送られているかをテストしたいことがあると思います。
今回はユーザー登録したユーザーにメールが送られているかをテストしてみます。

やり方

Notification Fakeというやつを使います。
Notificationファサードのfakeメソッドを使用すると、通知が送られるのを防ぐことができます。

SendMialTest.php

public function 会員通録したユーザーにメール通知が送られることを検証する()
{
    // fakeメソッド準備
    Notification::fake();
    // この段階では通知で送られていないことをアサートする
    Notification::assertNothingSent();
    
    // ユーザー登録用のサービスで登録処理を行う
    $request = ['name' => '田中たろう', 'email' => 'taro@example.com'];
    $user = (new CreateUserService())($requests);
    
    // 対象に通知が送られたことをアサート
    Notification::assertSentTo(
        $user,
        SendMail::class// Notificationを実行するクラス
    );
    // 通知が一度だけ送られてたことをアサート
    Notification::assertTimesSent(
        1,
        SendMail::class
    );
}

以上です。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?