Search code examples
mysqllaravelphpunitlaravel-5.5

How to create an in-memory database for PHPUnit testing?


I'm a newcomer to PHPUnit (and unit testing in general). I want to work on a test suite that developers can run locally, but can also be run in our integration system (Codeship). I understand that it is possible to use an in-memory database, but it seems like that relies on the migrations, which we are not using (doesn't seem to handle views, stored procedures, functions, triggers, etc very well?).

What's the best way (place in Laravel) to 1) create a database in memory and seed the database with default data (to be used for ALL test)?


Solution

  • You can use SQLite.

    From the docs:

    An SQLite database is normally stored in a single ordinary disk file. However, in certain circumstances, the database might be stored in memory.

    Add this to the config/database.php file:

    'sqlite_testing' => [
        'driver'   => 'sqlite',
        'database' => ':memory:',
        'prefix'   => '',
    ],
    

    On the phpunit.xml file, under <php> node:

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

    Read more here.

    Other solution

    Create a testing database on your storage/ folder, with the name database.sqlite or if you want another name or another location you have to change the configs on the config/database.php file, these are the default configs:

    'sqlite' => [
        'driver'   => 'sqlite',
        'database' => storage_path('database.sqlite'),
        'prefix'   => '',
    ],
    

    Use this command to run your migrations:

    php artisan migrate --database=sqlite
    

    Or add this line to the .env file:

    DB_CONNECTION=sqlite
    

    Your application is using sqlite for phpunit.

    Now you can run your migrations and test. After that, just change the DB_CONNECTION to the database you are using for your project.