Search code examples
laraveltestingphpunitlumen

While running laravel phpunit testcase , i'm getting an error "Call to a member function connection() on null" in Model.php line 1249


I'm running laravel phpunit testcase, getting error in DB connection. DB connected successfully. But,

"Call to a member function connection() on null" - Could not open to database connection server. Please update the configuration settings.

I did all those things properly. Find below details:

"php" : ">=7.1.3",
"laravel/lumen-framework": "5.8.*",
"phpunit/phpunit" : "^7.0",
"phpunit/php-invoker" : "*",
"phpunit/dbunit" : "^4.0",

Solution

  • This would be a bit of a guess without seeing your phpunit.xml configuration but I suspect you need to specify a connection for testing.

    If you check your php unit file you should have some values like below in your php property. Setting the DB_CONNECTION to sqlite and DB_DATABASE to :memory: is a fast and light-weight way to configure your testing DB.

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

    If you do have similar values in your phpunit.xml file then you will need to check your config/database.php file and ensure the connection matching your DB_CONNECTION has a sensible configuration.

    The default values for sqlite should work fine and are as follows:

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

    Hope this helps.