lordisp
lordisp

Reputation: 730

Laravel UnitTest -> environment variables are totally ignored

I'm about to run crazy!

I have a simple local Laravel setup on xampp (not php artisan serve) with mysql which runs fine. Now I want to setup phpunit. I read the Laravel docs, read tons of blog post and finally discovered YouTube.

I tried to use .env.testing, configured vars in phpunit.xml, I also tried a different connection block in config/database.php

I can do whatever I want, phpunit still takes the DB settings which a active in .env after running the php artisan config:cache

Even if I directly pass the .env.testing over by running php artisan test --env=testing, phpunit still takes the prod DB.

What did I miss to tell phpunit to take another DB in this configuration and don't ignore my env inputs on .env.testing or phpunit.xml?

.env:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=mydb
DB_USERNAME=root
DB_PASSWORD=

.env.testing:

DB_CONNECTION=mysql_testing
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=mydb_test
DB_USERNAME=root
DB_PASSWORD=

phpunit.xml:

<server name="APP_ENV" value="testing"/>
<server name="DB_CONNECTION" value="mysql_testing"/>
<server name="DB_DATABASE" value="mydb_test"/>

config/database.php:

'mysql' => [
    'driver' => 'mysql',
    'database' => env('DB_DATABASE', 'forge'),
...
]
'mysql_testing' => [
    'driver' => 'mysql',
    'database' => env('DB_DATABASE', 'forge'),
...
]

I have both DB: mydb and mydb_test

I've also testet this version:

config/database.php:

'mysql' => [
    'driver' => 'mysql',
    'database' => env('DB_DATABASE', 'mydb'),
...
]
'mysql_testing' => [
    'driver' => 'mysql',
    'database' => env('DB_DATABASE_TEST', 'mydb_test'),
...
]

...with DB_DATABASE_TEST=mydb_test in my phpunit.xml and .env

Phpunit still uses the mydb

Thanks!

Upvotes: 1

Views: 1661

Answers (3)

Mahdi Amiri
Mahdi Amiri

Reputation: 339

it's work for me

in your TestCase.php add:


public function __construct(?string $name = null, array $data = [], $dataName = '')
{
    parent::__construct($name, $data, $dataName);
    if(config('app.env') != "testing") {
        \Artisan::call('optimize:clear');
        $this->createApplication();
    }
}

Upvotes: 0

You need to check if your docker-compose.yml has:

- env_file: .env

It means that all your .env variables used into Laravel will be shared with container like environment variables. Every time you try to run your tests, the container will use APP_ENV based on .env in your project that probably has "local" by default. It will prevent your phpunit.xml be readed. It was my case...

Upvotes: 2

lordisp
lordisp

Reputation: 730

Thanks to Marcel Santing! With all my tries and different approaches, I simply did not run php artisan optimize:clear, which made the difference.

Upvotes: 0

Related Questions