Starting in 2019, there is now a way to create Laravel PHPunit tests for using a database in memory.
Configure SQLite In-memory for Laravel / Lumen tests
You should have the following:
- For all database migrations for all tables and files in your database, as is usually done for a real database, see the official Laravel migration documents .
RefreshDatabase trait ( DatabaseMigrations trait for Lumen) in your PHPUnit test class (white papers ).- Install the following in the
config/database.php file in the connection section:
'testing' => [ 'driver' => 'sqlite', 'database' => ':memory:', ],
- Install the following line in the
phpunit.xml file in the <php> section:
<env name="DB_CONNECTION" value="testing"/>
Thus, as soon as you run your PHPUnit tests, PHPUnit will read phpunit.xml , replace the .env DB_CONNECTION variable with testing . This will force you to use the testing database configuration (which is the database in memory).
Tests with a database in RAM against a disk database (in my experience) are about 5-30 times faster. The difference is 30 times for a small set of tests of ~ 200 CRUD tests, all of which fulfill database queries for half a dozen tables with some hasMany and belongsToMany .
And yes, migrations will be performed before and after each test, so you will start and finish working with a clean database after the tests are completed (this will have consequences if you add some data to the database on the disk and switch tests from time to time to work on dumb, not on the database in memory).
Fix SQLite Cannot add a NOT NULL column with default value NULL
You have now successfully set up in-memory database testing for your application. If you try to use foreign keys to cascade changes to some related tables, the above error is expected.
If you quickly switch your tests to the database on the disk (comment out <env name="DB_CONNECTION" value="testing"/> in your phpunit.xml file), the error will disappear. After switching back to the database in memory, make sure that the database on the disk is not empty. If so, run migrate:refresh and db:seed (here it is assumed that you have already prepared the database seeds you need) with artisan .
By default, SQLite disables foreign keys. To fix this, add the following snippets to your PHPUnit test class:
See detailed explanations and other, better, different solutions here .
Hope this clarifies the topic enough to work without problems.