LoginSignup
1
0

More than 3 years have passed since last update.

PHPUnitでスローされた例外をテストする

Last updated at Posted at 2020-09-25

結論

以下のように書こう🍄

    /**
     * @test
     * @return void
     */
    public function insertHoge_異常_{エラー内容}()
    {
        // スローを期待する例外の内容
        $this->expectException(例外クラス);
        $this->expectExceptionMessage(例外メッセージ);

        $param = 不正な値;

        // 例外をスローするテスト対象メソッド
        $this->reportService->insertHoge($param);
    }

事例

    /**
     * @test
     * @return void
     */
    public function addRecord_異常_外部キー不正()
    {
        $this->expectException(Exception::class);
        $this->expectExceptionMessage('a foreign key constraint fails');

        $id = 'invalidId';

        $this->reportService->insertHoge($id);
    }

Tips

  • expectExceptionMessage()による例外メッセージ検証は、部分一致で判定できる
  • timestampの値を観点にしないテスト等、
    観点に含まれない無いが実行タイミングによって変化する値を含むエラーメッセージの検証を行う場合は便利

例)
 上記事例のテスト実行時に返却される例外メッセージ全文

'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`hoge_db`.`hoge_table`, CONSTRAINT `user_id_foreign` FOREIGN KEY (`id`) REFERENCES `users` (`id`)) (SQL: insert into `hoge` (`id`, `updated_at`, `created_at`) values (0, 2020-09-25 11:31:05, 2020-09-25 11:31:05))'
1
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
1
0