はらへり日記

腹に弾丸

PHPUnitで例外を投げた後の処理をテストする

例えばこんなクラスコードがあるとする。

<?php

namespace App;

use Psr\Log\LoggerInterface;
use App\Util\DB;
use App\Exception\DbException;

class BlogService
{
    /** @var DB */
    protected $db;

    /** @var LoggerInterface */
    protected $logger;

    public function __construct(DB $db, LoggerInterface $logger)
    {
        $this->db = $db;
        $this->logger = $logger;
    }

    public function createNewPost(int $userId, string $title)
    {
        $this->db->begin();

        try {
            $postRow = $this->db->insert('posts', [
                'title' => $title,
            ]);

            $this->db->insert('post_user_relations', [
                'user_id' => $userId,
                'post_id' => $row['post_id'],
            ]);

            $this->db->commit();
        } catch (DbException $e) {
            $this->logger->warning($e->getMessage());
            $this->db->rollback();

            throw $e;
        }

        return $postRow['post_id'];
    }
}

ブログを投稿する簡単なクラス。

INSERT文を2つ発行するのでトランザクションを貼って、もしデータベース例外が発生したらloggingした上で例外を投げ直すというよくあるコード。

これに対してテストコードをPHPUnitで書いてみる。

テスト方針

スタンダードに以下のようなテストケースを書いてみる。

  • INSERT処理が2回とも通り、期待する結果を返せばpost IDを返す
  • INSERTがどちらかコケたらログを取った上で例外を投げる

上記のクラスはきれいにDIパターンで実装されているのでいずれのテストもモックを注入し、振る舞いを指定することでロジックの保証をするテストが書ける。

後者のテストを実装するならこんな感じ。

<?php

namespace App;

use Mockery as m;
use Psr\Log\LoggerInterface;
use App\Util\DB;
use App\Exception\DbException;

class BlogServiceTest
{
    /** @var DB */
    protected $db;

    /** @var LoggerInterface */
    protected $logger;

    public function setUp()
    {
        $this->db = m::mock(DB::class);
        $this->logger = m::mock(LoggerInterface::class);
    }

    /**
     * @expectedException DbException
     */
    public function testCreateNewPostSholdThrowExceptionWithLogging()
    {
        $this->db->shouldReceive('insert')->andThrow(new DbException());
        $this->db->shouldReceive('rollback')->once(); // Rollbackすることをテスト
        $this->logger->shouldReceive('warning')->once(); // Loggingすることをテスト

        $SUT = new BlogService($this->db, $this->logger);

        $SUT->createNewPost(1235, 'title');
    }
}

色々はしょってるけどだいたいこんな感じになると思う。

ただ、現実のサービスはこんな単純な仕様であることはほぼない。

例えばここに追加仕様で「例外を投げたらloggingし、rollbackし、エラーをテキストファイルに吐き出すようにする」みたいなものが来たとする。(いい例えが思いつかなかっただけで、現実的にはもっと別のケースがあるでしょう)

こんなコード。

<?php

    /** ~ */

    public function createNewPost(int $userId, string $title)
    {
        $this->db->begin();

        try {
            $postRow = $this->db->insert('posts', [
                'title' => $title,
            ]);

            $this->db->insert('post_user_relations', [
                'user_id' => $userId,
                'post_id' => $row['post_id'],
            ]);

            $this->db->commit();
        } catch (DbException $e) {
            $this->logger->warning($e->getMessage());
            $this->db->rollback();
            // ここが追加
            file_put_contents('path/to/file.txt', json_encode($e));

            throw $e;
        }

        return $postRow['post_id'];
    }

これに対して先程のテストコードだと「エラーをテキストファイルに吐き出す」ことの確認ができない。

しかしファイル書き込みロジックは外部注入していないのでモックすることもできない。

そこでこんなテストを書いてみるとする。

<?php

namespace App;

use Mockery as m;
use Psr\Log\LoggerInterface;
use App\Util\DB;
use App\Exception\DbException;

class BlogServiceTest
{
    /** @var DB */
    protected $db;

    /** @var LoggerInterface */
    protected $logger;

    public function setUp()
    {
        $this->db = m::mock(DB::class);
        $this->logger = m::mock(LoggerInterface::class);
    }

    public function testCreateNewPostSholdThrowExceptionWithLogging()
    {
        $this->db->shouldReceive('insert')->andThrow(new DbException());
        $this->db->shouldReceive('rollback')->once(); // Rollbackすることをテスト
        $this->logger->shouldReceive('warning')->once(); // Loggingすることをテスト

        $SUT = new BlogService($this->db, $this->logger);

        // 例外投げられるとチェックできないからcatchする
        try {
            $SUT->createNewPost(1235, 'title');
        } catch (DbException $e) {
            $this->assertTrue(file_exists('path/to/file.txt'));
            return;
        }
   
        $this->fail();
    }
}

例外を投げられた後だとプログラムが続行できないので例外をcatchしてassertionする。

また、例外をcatchできなかったらテストをコケるようにして例外を投げることを保証する。

これで一件落着、と思いきやこの書き方には2つ問題がある。

  • テストの書き方によってはスタックトレースが表示されず何がなんだか分からない
  • テストの中にロジックが混ざって可読性が下がる

前者に関しては以下のようなテストの書き方をしてると起きる。

<?php

// 例外投げられるとチェックできないからcatchする
try {
    $SUT->createNewPost(1235, 'title');
} catch (\Exception $e) {
    $this->assertInstanceOf(DbException::class, $e);
    $this->assertTrue(file_exists('path/to/file.txt'));
    return;
}

こんな書き方しなきゃいいじゃんって話なんだけど、時たまやるしテストやロジックが複雑化していけばなおさら起きる。

とはいえこういうことは往々にして起きるのでもう少し違うアプローチを考えることにした。

テストを分ける

シンプルにテストを分けてコケたときのエラートラッキングを分けるようにする。

具体的には「意図した例外が投げられること」と「例外が投げられた後の状態が望みどおりであること」の2ケースに分ける。

イメージ的にはこんな感じ。

<?php

namespace App;

use Mockery as m;
use Psr\Log\LoggerInterface;
use App\Util\DB;
use App\Exception\DbException;

class BlogServiceTest
{
    /** @var DB */
    protected $db;

    /** @var LoggerInterface */
    protected $logger;

    public function setUp()
    {
        $this->db = m::mock(DB::class);
        $this->logger = m::mock(LoggerInterface::class);
    }

    /**
     * @expectedException DbException
     */
    public function testCreateNewPostSholdThrowExceptionWithLogging()
    {
        $this->db->shouldReceive('insert')->andThrow(new DbException());
        $this->db->shouldReceive('rollback')->once(); // Rollbackすることをテスト
        $this->logger->shouldReceive('warning')->once(); // Loggingすることをテスト

        $SUT = new BlogService($this->db, $this->logger);

        $SUT->createNewPost(1235, 'title');
    }

    public function testCreateNewPostSholdPutFileAfterThrowException()
    {
        $this->db->shouldReceive('insert')->andThrow(new DbException());

        $SUT = new BlogService($this->db, $this->logger);

        try {
            $SUT->createNewPost(1235, 'title');
        } catch (DbException $e) {
            // 例外をthrow後の状態をテストする
            $this->assertTrue(file_exists('path/to/file.txt'));
        }
    }
}

こうすることで意図しない例外が発生しても原因の切り分けが多少やりやすくなる。

また、もう少し改善する点としてこの2ケースは前者がコケた時点で後者をテストする必要がない。

そこで@dependsアノテーションを利用して前者がコケたら後者がコケるようにする。

<?php

namespace App;

use Mockery as m;
use Psr\Log\LoggerInterface;
use App\Util\DB;
use App\Exception\DbException;

class BlogServiceTest
{
    /** @var DB */
    protected $db;

    /** @var LoggerInterface */
    protected $logger;

    public function setUp()
    {
        $this->db = m::mock(DB::class);
        $this->logger = m::mock(LoggerInterface::class);
    }

    /**
     * @expectedException DbException
     */
    public function testCreateNewPostSholdThrowExceptionWithLogging()
    {
        $this->db->shouldReceive('insert')->andThrow(new DbException());
        $this->db->shouldReceive('rollback')->once(); // Rollbackすることをテスト
        $this->logger->shouldReceive('warning')->once(); // Loggingすることをテスト

        $SUT = new BlogService($this->db, $this->logger);

        $SUT->createNewPost(1235, 'title');
    }

    /**
     * @depends testCreateNewPostSholdThrowExceptionWithLogging
     */
    public function testCreateNewPostSholdPutFileAfterThrowException()
    {
        $this->db->shouldReceive('insert')->andThrow(new DbException());

        $SUT = new BlogService($this->db, $this->logger);

        try {
            $SUT->createNewPost(1235, 'title');
        } catch (DbException $e) {
            // 例外をthrow後の状態をテストする
            $this->assertTrue(file_exists('path/to/file.txt'));
        }
    }
}

これで完璧!!

テストを書くのは楽しいね。