How to specify a different .env file for phpunit in Laravel 5

Copy your .env to .env.testing, then edit the .env.testing file and change the APP_ENV parameter to make it like this APP_ENV=testing this way you will be able to specify your settings int this new file

In case you don’t want to create a new .env.testing file you have to specify your variables in the phpunit.xml in the php section with the values you need, something like this

<php>
    <env name="APP_ENV" value="testing"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="QUEUE_DRIVER" value="sync"/>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value="testing"/>
</php>

Just use the key values in the name section and the value of that key in the value section.

For this example I am specifying phpunit to use an sqlite database with the name of testing.

By the way in config/database.php I added this 'default' => env('DB_CONNECTION', 'mysql'), to use mysql by default unless I specify something diferent, as in this case.

You could override the .env file being used in your TestCase file, where the framework is booted for testing.

More specific:

tests/TestCase.php

/**
 * Creates the application.
 *
 * @return \Illuminate\Foundation\Application
 */
public function createApplication()
{
    /* @var \Illuminate\Foundation\Application $app */
    $app = require __DIR__ . '/../bootstrap/app.php';
    $app->loadEnvironmentFrom('.env.testing'); // specify the file to use for environment, must be run before boostrap
    $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
    return $app;
}

All the tests extending TestCase will use this configuration file.

Please note that any setting defined in phpunit.xml will override this configuration.

Update

Starting Laravel5.4, the createApplication function is no longer found in tests\TestCase. It has been moved to tests\CreatesApplication trait.