This is a straightforward How to Config article if you are looking to test your unit and feature lest in Laravel with phpunit along with SQLite Database.

Following are the steps.

 

Open your database.php file located under config folder and make sure you have sqlite database added in your connections array.

'sqlite' => [
     'driver' => 'sqlite',
     'database' => env('DB_DATABASE', database_path('database.sqlite')),
     'prefix' => '',
],

 

Open file phpunit.xml which is located at the root directory of your project and make following changes for the database connection.

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

 

Notice that we have used value :memory: for DB_CONNECTION variable. This will make sure that the testing database and the related transactions all take place in memory instead of a physical file.

 

Now coming to the phpunit test. You need to import DatabaseMigrations class in your test, This will make sure that every time you run your tests the migration file is executed.

Following is an ExampleTest

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

 

 

Comments