自動テスト(PHPUnit)、例外を処理する。

PHPUnitで例外を検証したい場合は以下のように書くと良いです。


/** * @test * @return void */ public function 例外が出力されること() { $this->expectException(InvalidArgumentException::class); // 期待される例外のクラス $this->expectExceptionMessage("Message"); // 例外によって出力される任意のメッセージ $obj = new Example(); $someInvalidArgument = "Invalid Argument"; $obj->throwExceptionMethod($someInvalidArgument); // 例外が出力されるであろう処理 }

ポイントはexpectExceptionなどの期待される出力に関する規定を、実行したい処理よりも上に書くことです。