LoginSignup
0
0

More than 1 year has passed since last update.

【Laravel 9.12】例外が発生することをテストする方法 assertThrows()

Last updated at Posted at 2023-02-13

assertThrows()

Laravel 9.12 以降で可能です。

例外が発生する関数を引数に指定することで検証を行えます。

使用例

例外が発生することを確認する

$this->assertThrows(fn () => throw SomeException(''));

特定の例外が発生することを確認する

$this->assertThrows(
    fn () => maybeExceptionThrownFunction(),
    CustomException::class,
);

特定のメッセージを持った例外が発生することを確認する

$this->assertThrows(
    fn () => throw Exception('My message'), 
    Exception::class,
    'My message',
);

expectException()との違い

expectException()は例外を発生させる前に呼び出すことで発生した例外を検証することが可能ですが、
例外が発生した時点でテストは終了してしまうため他のアサーションと組み合わせることなどはできません。
assertThrows()は例外を引数の関数内で検証できるため、
テスト自体を終了せずに他のアサーションを実行することも可能です。
同じ関数から複数の例外を検証する場合などもexpectException()では、
確認したい例外の数だけテストメソッドを増やす必要がありますが、
assertThrows()は1つのテストメソッドでまとめれるためスッキリ書くことができます。

コードの比較
public function testExpectException(): void
{
    $this->expectException(Excepiton::class);

    throwExceptionsFunction();

    // 以下は実行されない
    $this->assert...
    ...
}

public function testAssertThrows(): void
{
    $this->assertThrows(
        fn () => throwExceptionsFunction(),
    );

    // 実行される!
    $this->assert...
    ...

    // 続けて別の例外を検証することもできる!
    $this->assertThrows(
        fn () => throwExceptionsFunction(),
        AnotherException::class,
    );
}

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