0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHPUnit で一度だけDBリセットする

Posted at

テスト実施時にDBリセットをしたかったのですが、
テストファイルが変わるたびにDBテーブル作成をしていたので
これを1回のみ実行させるようにしたくてためしたことです

前提

sailでプロジェクトを作成している
テストフレームワークはPHPUnitを指定している

実装

デフォルトでは何も書かれていないので追加

tests/TestCase.php
<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\DB;

abstract class TestCase extends BaseTestCase
{
    protected static bool $migrated = false;
    protected function setUp(): void
    {
        parent::setUp();
        if(self::$migrated === false) {
            $this->artisan('db:wipe', ['--database' => env('DB_CONNECTION', 'mysql')]);
            $this->artisan('migrate --force');
            self::$migrated = true;
        }

        DB::beginTransaction();
    }

    protected function tearDown(): void
    {
        DB::rollback();

        parent::tearDown();
    }
}

蛇足

データベース名は phpunit.xml から変更できます
※ testingデータベースはsailでプロジェクトを作成した場合、初回コンテナ作成時に作成されます

phpunit.xml
...以上省略
    <php>
        ...
        <env name="DB_DATABASE" value="testing"/>
...以下省略

データベース接続がうまくいかない場合、環境変数に原因があるかもしれません

SQLSTATE[HY000] [2002] Connection refused (Connection: mysql, 
  • .env の DB_HOST にはDBコンテナ名を指定しているか
  • config/database.php に接続設定があるか
  • .env の DB_PORT , DB_USERNAME , DB_PASSWORD に間違いがないか
    2重に定義していないか
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?