simpsons3
simpsons3

Reputation: 991

Laravel PHPUnit auto chose default connection

I'm trying to writing testing in Laravel with phpunit. However, when I run testing by php artisan test, laravel auto write and refresh on my main database. I've tried to create another database and set phpunit run with it but it doesn't work.

This is my phpunit.xml config:

    <php>
        <server name="APP_ENV" value="local"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="DB_CONNECTION" value="testing"/>
        <server name="DB_DATABASE" value="main_testing"/>
        <server name="MAIL_MAILER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
        <server name="TELESCOPE_ENABLED" value="false"/>
    </php>

The .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=main
DB_USERNAME=root
DB_PASSWORD=

DB_TEST_CONNECTION=testing
DB_TEST_HOST=127.0.0.1
DB_TEST_PORT=3306
DB_TEST_DATABASE=main_testing
DB_TEST_USERNAME=root
DB_TEST_PASSWORD=

Config connections in config/database.php:

'testing' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_TEST_HOST', '127.0.0.1'),
    'port' => env('DB_TEST_PORT', '3306'),
    'database' => env('DB_TEST_DATABASE', 'forge'),
    'username' => env('DB_TEST_USERNAME', 'forge'),
    'password' => env('DB_TEST_PASSWORD', ''),
    'unix_socket' => env('DB_TEST_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

I've add some code to test in Feature\ExampleTest.php:

    public function testBasicTest()
    {
        $admin = \App\Models\Admin::factory(10)->create();
        $response = $this->get('/');
        $response->assertStatus(200);
    }

When I run php artisan test, I want records created in main_testing database but it keeps creating in main database.

Anyone can help?

Upvotes: 0

Views: 572

Answers (2)

Plumpboy
Plumpboy

Reputation: 45

I had the same error and i find that config in phpunit.xml can fix. Let give it a try.

<server name="APP_ENV" value="testing"/>

Upvotes: 0

simpsons3
simpsons3

Reputation: 991

I just have figured out reason why it don't work. It's because I ran php artisan config:cache instead of php artisan config:clear. If I run config:cache, laravel will clear all cached configuration and cached it again. Thus, all configuration in phpunit.xml is ignored and testing will run with main database.

I also find a simple solution to prevent database from deleted while test. Just add some configuration checks in CreatesApplication trait to make sure you are not using develop database for testing.

Upvotes: 1

Related Questions