Quantcast
Channel: 例外タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 100

laravel phpunit お手軽例外処理のテスト

$
0
0

◆方法

・try catch
・exceptedException
・exceptedExceptionアノテーション(非推奨)

◆try catch

class ExampleTest extends TestCase
{
    private $errorMessageOverFlow = 'overFlowException';
    private $errorCodeOverFlow    = 999;

    public function testException()
    {
        try{
            throw new \OverflowException($this->errorMessageOverFlow, $this->errorCodeOverFlow);
        }catch (\Throwable $e){
            //とんできたクラスがこのクラスのインスタンスかチェック
            $this->assertInstanceOf(\OverflowException::class, $e);
            //とんできたエラーメッセージが同じかチェック
            $this->assertSame($this->errorMessageOverFlow, $e->getMessage());
            //とんできたエラーコードが同じかチェック
            $this->assertSame($this->errorCodeOverFlow, $e->getCode());
        }
    }
}

◆exceptedException

class ExampleTest extends TestCase
{
    private $errorMessageOverFlow = 'overFlowException';
    private $errorCodeOverFlow    = 999;

    public function testException()
    {
        //指定したクラスが例外で投げられてるかチェック
        $this->expectException(\OverflowException::class);
        //指定したメッセージかチェック
        $this->expectExceptionMessage($this->errorMessageOverFlow);
        //指定したコード
        $this->expectExceptionCode($this->errorCodeOverFlow);

        throw new \OverflowException($this->errorMessageOverFlow, $this->errorCodeOverFlow);
    }
}

try~catchとの違いは、例外をなげるクラスの前に書くことで、検証することができるという点です。

◆exceptedExceptionアノテーション(非推奨)

コメントしていただいた方から教えていただきましたが、最新版ではアノテーションは非推奨のためphpコードで書くようにする。

class ExampleTest extends TestCase
{
    private $errorMessageOverFlow = 'overFlowException';
    private $errorCodeOverFlow    = 999;

    /**
     * @expectedException \OverflowException
     * @expectedExceptionMessage overFlowException
     * @expectedExceptionCode 999
     */
    public function testException()
    {
        throw new \OverflowException($this->errorMessageOverFlow, $this->errorCodeOverFlow);
    }
}

コメントの中にアノテーションを使ってそれぞれ指定してあげます。この時にメッセージやコードを変数で入れることはできないので、直接書き込んでおります。

◆まとめ

色々な例外など知らないことがめちゃくちゃたくさんありました。つぎから、例外処理を書くときは、その処理の例外にあったものを選択できるようにしっかり調べて、使いたいです。

◆参考にさせていただいた記事

phpunit例外処理
いろいろな例外
いろいろなassertメソッド


Viewing all articles
Browse latest Browse all 100

Trending Articles