LoginSignup
0
0

【Laravel11.x】例外(Exception)のテストはExceptions::fake()が便利

Posted at

はじめに

例外が投げられたか?をテストするとき、決まり事のようにexpectExceptionを使ってましたがExceptionsという便利なファサードが増えていたのでメモ

Exceptionsファサードを使用するにはLaravel11.4 以上が必要です

例外が発生したことをテストしたいとき

HogeTest.php
use Illuminate\Support\Facades\Exceptions;
use App\Exceptions\FugaException;

Exceptions::fake();

// テストしたい処理をここで実行する

// FugaExceptionが発生したことをアサート
Exceptions::assertReported(FugaException::class);

// コールバックも可能
// 以下の例はキャッチしたFugaExceptionのメッセージが'The order was invalid.'の場合のみ成功する
Exceptions::assertReported(function (FugaException $e) {
    return $e->getMessage() === 'The order was invalid.';
});

例外が発生しないことをテストしたいとき

HogeTest.php
use Illuminate\Support\Facades\Exceptions;
use App\Exceptions\FugaException;

Exceptions::fake();

// テストしたい処理をここで実行する

// FugaExceptionが発生して"いない"ことをアサート
Exceptions::assertNotReported(FugaException::class);

// なんの例外も発生して"いない"ことをアサート
Exceptions::assertNothingReported();

特定の例外だけテストしたいとき

HogeTest.php
use Illuminate\Support\Facades\Exceptions;
use App\Exceptions\FugaException;
use App\Exceptions\PiyoException;

// FugaExceptionをのみテスト
Exceptions::fake(FugaException::class);

// FugaExceptionが投げられても処理続行
throw new FugaException('fakeしているので処理はここで止まらない');

// FugaExceptionが発生していることをアサート→true
Exceptions::assertReported(FugaException::class);

// PiyoExceptionはExceptions::fakeに入っていないので、ここで処理が止まる
throw new PiyoException('fakeしていないので処理はここで止まる');
HogeTest.php
// 配列で複数指定することもできます
Exceptions::fake([FugaException::class, PiyoException::class]);

expectException()ぽい書き方もできる

例外のテストで調べると大体でてくるexpectExceptionっぽい書き方もできます

HogeTest.php
use Illuminate\Support\Facades\Exceptions;
use App\Exceptions\FugaException;

Exceptions::throwOnReport([FugaException::class]);

throw new FugaException();

// FugaExceptionが発生したのでthrowOnReportは成功します

この場合最初にEvent::fake()を書かなくてもOKです

おわりに

公式ドキュメントをみて知識をアップデートしていかないと、あっという間に古い知識になっていきますね。

ExeptionsファサードはassertThrowsexpectExceptionに比べて可読性が高いと思うので、どんどん使っていきたいです

参考

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