0
0

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 3 years have passed since last update.

LaravelでNotification::fake()を使ったテストでNotification::assertSentToがうまく通らない

Last updated at Posted at 2021-03-03

経緯

Laravelのテストで、Notification Fake
https://readouble.com/laravel/8.x/ja/mocking.html
を使用して、テスト時に実際にはslackに通知を飛ばさないようにしておいて、
Notification::assertSentTo
で、通知が送信される処理は行われていることをテストしようとして、

Notification::assertSentTo(
    new AnonymousNotifiable,
    SlackNotification::class
);

と書いたのだけど、どうあがいても

The expected [App\Notifications\SlackNotification] notification was not sent.
Failed asserting that false is true.

と怒られてしまう。
指定の仕方とか色々試したけど、assertSentToではどうあがいてもうまくテストが通らなかった。。。。

解決策

Notification::assertTimesSent
を使用することで解決

Notification::assertTimesSent(
    1,
    SlackNotification::class
);

第一引数に通知が送信されるべき回数(期待値)を指定してやればOK
テストでは一旦通知内容は確認しなくてOKだったので、通知が飛ばされる回数をテストしてやる形でテストが通った

通知が送られる処理の直前で

Notification::assertTimesSent(
    0,
    SlackNotification::class
);

と記述しても通ったので、とりあえず問題なさそう。

assertSentTo使う場合はどう書けばいいのかモヤモヤするけど、一旦忘れる!

追記

本記事を公開後、ちょっと調べてたら、以下の記事を見つけた
https://qiita.com/harukei/items/26f0a1c0d6128f681c00
Notification::fake() が Mail::fake() を上から潰しているようです。

確かに僕のコードでも

    public function test__invoke()
    {
        Mail::fake();
        Notification::fake();

とNotification::fake() と Mail::fake()の両方を使用しているので、assertSentToがうまく動作しないのはこのせいなのかもしれない。。。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?