LoginSignup
42
40

More than 5 years have passed since last update.

俺がLaravel 4でユニットテストするときのTestCaseクラス

Last updated at Posted at 2014-03-27

自分がLaravel 4でユニットテストするときのTestCaseクラス。

ソースコード

app/tests/TestCase.php
namespace App\Tests;

use Artisan;
use DB;
use Mockery as m;

class TestCase extends \Illuminate\Foundation\Testing\TestCase
{
    /**
     * データベースの利用フラグ
     */
    protected $useDatabase = true;

    /**
     * Creates the application.
     *
     * @return Symfony\Component\HttpKernel\HttpKernelInterface
     */
    public function createApplication()
    {
        $unitTesting = true;

        $testEnvironment = 'testing';

        return require __DIR__.'/../../bootstrap/start.php';
    }

    public function setUp()
    {
        parent::setUp();

        // データベースの初期処理
        if ($this->useDatabase) {
            $this->setUpDb();
        }
    }

    public function tearDown()
    {
        parent::tearDown();

        // Mockeryコンテナのクリーンアップ
        m::close();

        // データベースの終期処理
        if ($this->useDatabase) {
            $this->tearDownDb();
        }
    }

    protected function setUpDb()
    {
        // テーブル作成、テストデータ登録
        Artisan::call('migrate');
        Artisan::call('db:seed');
    }

    protected function tearDownDb()
    {
        // テーブル削除
        Artisan::call('migrate:reset');

        // データベースから切断
        DB::disconnect();
    }
}

説明

  • このサイトを参考にMockeryを統合。
  • テストコードにも名前空間を切る。
  • setUp()でマイグレーションとシードを実行してテストデータをデータベースに投入する。
  • tearDown()で全部のテーブルを削除してデータベースから切断する。DB::disconnect()しないと「Too many connections」エラーで怒られる(MySQL + Eloquentの場合。他は不明)。
  • テスト時間を少しでも短縮したいので、データベースを使わないテストでは$useDatabasefalseにしてマイグレーションとシードの実行をスキップする。
42
40
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
42
40