Configuring a Test Database Using Laravel and PHPUnit

Database Testing

Committed to the LaraBrain by: wjgilmore (@wjgilmore) at October 26, 2015 7:32 pm

Configure a test database in the most flexible fashion using Laravel and PHPUnit

Laravel's application testing features are now so user friendly that Laravel developers simply no longer have any excuses for not writing automated tests.

Among the many test-related conveniences offered to you is the ability to configure a test database which will be used as a repository for all data created while running your test suite. Laravel will automate the creation and destruction of the very same tables you created through migrations, for each and every test, ensuring a pristine test environment. You can even use the config/database.php and .env files to manage the test database in the very same fashion used to manage your development and production databases. To identify a new database for test purposes, open the config/database.php file and add a new entry to the connections array:

'connections' => [
    'mysql_test' => [
        'driver'    => 'mysql',
        'host'      => env('DBT_HOST', 'localhost'),
        'database'  => env('DBT_DATABASE', 'forge'),
        'username'  => env('DBT_USERNAME', 'forge'),
        'password'  => env('DBT_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,

This connection alias is called mysql_test, and it refers to several environment variables used to connect to the database (DBT_HOST, DBT_DATABASE, DBT_USERNAME, and DBT_PASSWORD). Place these environment variables in your .env file:


Finally, open the phpunit.xml file and add the following line to the php enclosure:

<env name="DB_CONNECTION" value="mysql_test"/>

With this configuration in place, Laravel will now know which database should be used when your tests interact with a database.