LoginSignup
0
0

More than 1 year has passed since last update.

$this->expectException()を使うとAssert文が使えない

Last updated at Posted at 2023-02-25

概要

こんな感じで例外時にAssert文を使ってDBがロールバックされているか確認したかった、、、
けど、$this->expectException()を使うとAssert文のところまで処理が行かないまま、ユニットテスト通過してしまっていることが発覚。

CreateUserServiceTest.php
/**
 * @test
 */
public function エラー時ロールバックされるかテスト()
{
    $this->expectException(Exception::class);
    
    $request = ['name' => 'テスト太郎']
    $service = new CreateUserService();
    ($service)($request);
    
    // ここまで処理が到達しておらず、ロールバックされているかがわからない
    $this->assertDatabaseMissing('users', [
        'name' => $request->name,
    ]);
}

解決方法

try catchを使う!

$this->expectException()は使いません。

UpdateUserServiceTest.php
public function エラー時ロールバックされるかテスト()
{
    $request = ['name' => 'テスト太郎']
    $service = new CreateUserService();

    try {
        ($service)($request);
    } catch (Exception $e) {
        $this->assertStringContainsString(
            '登録に失敗しました。',
            $e->getMessage()
        )
    }
    
    $this->assertDatabaseMissing('users', [
        'name' => $request->name,
    ]);
}

try catchして、テストを失敗させた上で、次の処理に進むようにします。

処理の順番としては、

ExceptionTest.php
public function エラー時ロールバックされるかテスト()
{
    //1. エラーが出るようなデータやモックの準備

    try {
        //2.メソッドを実行する
    } catch (Exception $e) {
        //3.失敗するので、エラーメッセージが適切か確認する
        $this->assertStringContainsString(
            '登録に失敗しました。',
            $e->getMessage()
        )
    }
    
    // 4.ロールバックされているか確認する
    $this->assertDatabaseMissing('users', [
        'name' => $request->name,
    ]);
}

以上です。

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