1
0

More than 3 years have passed since last update.

【phpunit】テストを実行するたびにローカルDBがリセットされる

Posted at

はじめに

phpunitを使ってテストを書いた際に、テストを実行するたびにローカルDBがリセットされるというバグにハマったので、解決方法を記録しておきます。

開発環境

PHP 7.4.16
Laravel 6.20.17
mysql 8.0.23
nginx 1.18.0

DB設定方法

ControllerTest.php に下記を追加

use Illuminate\Foundation\Testing\DatabaseTransactions;


class ControllerTest extends TestCase
{
    use DatabaseTransactions;
}

phpunit.xmlを下記にする

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>

        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="MAIL_DRIVER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
    </php>
</phpunit>

この時のポイントは、テスト用のデータベース(ローカルと同じ)を見るように設定すること!

下記の様な記載がphpunit.xmlにある時は、削除する!!

<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/> 
1
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
1
0