はじめに
例外が投げられたか?をテストするとき、決まり事のように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ファサードはassertThrows
やexpectException
に比べて可読性が高いと思うので、どんどん使っていきたいです
参考