Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fbunadi's avatar

Problem with Testing in Laravel Sail

Hi all,

1st time poster here, so please go easy on me. I'm creating a pest unit test that requires database connection to test User Model however I keep getting the error "Call to a member function connection() on null". I have no issue for the application connecting to the default database. This error only happens on my test unit.

My other Laravel Sail project has no issue connecting to the database for both the application and the test unit. They have the same setup so I'm not sure why this one doesn't work.

Framework: Laravel 11 + Sail Plugins: Redis, Memcached, Laravel Filament PHP Test: PEST

Error:

Call to a member function connection() on null

  at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1825
    1821▕      * @return \Illuminate\Database\Connection
    1822▕      */
    1823▕     public static function resolveConnection($connection = null)
    1824▕     {
  ➜ 1825▕         return static::$resolver->connection($connection);
    1826▕     }
    1827▕ 
    1828▕     /**
    1829▕      * Get the connection resolver instance.

      +8 vendor frames 
  tests/Unit/UserModelTest.php:10

Here's the test code

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('has the right attribute and association', function(){
    $user = User::create([
        'name' => 'John Doe',
        'firstname' => 'John',
        'lastname' => 'Doe',
        'email' => '[email protected]',
        'role_id' => 2,
        'uuid' => '3820202',
        'user_id' => 4
    ]);

    $this->assertDatabaseHas('users', [
        'name' => 'John Doe',
        'firstname' => 'John',
        'lastname' => 'Doe',
        'email' => '[email protected]',
        'role_id' => 2,
        'uuid' => '3820202',
        'user_id' => 4
    ]);
});

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
>
    <testsuites>
        <testsuite name="Unit">
            <directory>tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory>tests/Feature</directory>
        </testsuite>
    </testsuites>
    <source>
        <include>
            <directory>app</directory>
        </include>
    </source>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="APP_MAINTENANCE_DRIVER" value="file"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_STORE" value="array"/>
        <env name="DB_DATABASE" value="testing"/>
        <env name="MAIL_MAILER" value="array"/>
        <env name="PULSE_ENABLED" value="false"/>
        <env name="QUEUE_CONNECTION" value="sync"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="TELESCOPE_ENABLED" value="false"/>
    </php>
</phpunit>

Thanks for your help.

Fran

0 likes
2 replies
LaryAI's avatar
Level 58

Hello Fran,

The error you're encountering, "Call to a member function connection() on null," typically indicates that Laravel's model can't resolve the database connection. This is often due to the database setup not being correctly initialized or recognized in the testing environment. Here are a few steps to troubleshoot and potentially resolve this issue:

  1. Ensure Database Configuration for Testing: Make sure that your .env.testing file (or the environment configuration used for testing) is correctly set up with the appropriate database connection settings. Since you're using Laravel Sail, ensure that the DB_DATABASE and other related settings match the database service configurations in your docker-compose.yml.

  2. Database Migrations: Ensure that the database migrations are running as part of your test setup. You can use the RefreshDatabase trait, which you're already using, but make sure it's effectively resetting your database state before tests run. You can explicitly run migrations by adding the following in your test setup:

    $this->artisan('migrate', ['--database' => 'testing']);
    
  3. Check Database Connection in Test: Before performing operations in your test, check if the database connection is available. You can add a simple check like this at the beginning of your test function:

    it('checks database connection', function () {
        $this->assertNotNull(DB::connection()->getPdo());
    });
    
  4. Configuration Caching: Sometimes, configuration caching might cause issues during testing. Make sure to clear your configuration cache when switching environments. You can run:

    php artisan config:clear
    

    Alternatively, ensure that your testing environment does not cache configurations or that it uses a separate cache file.

  5. Inspect PHPUnit Configuration: Review your phpunit.xml file settings. Ensure that the environment variables under the <php> tag are correctly set and are not being overridden somewhere else in your configuration.

  6. Debugging Further: If the above steps don't resolve the issue, you might want to add more logging around the point of failure to understand what exactly is null. Modify the resolveConnection method temporarily in your local vendor files to log more details or to throw a more descriptive exception.

Here's a quick example of how you might modify a test to include a connection check and explicit migration:

uses(RefreshDatabase::class);

it('has the right attribute and association', function () {
    $this->artisan('migrate', ['--database' => 'testing']);
    $this->assertNotNull(DB::connection()->getPdo());

    $user = User::create([
        'name' => 'John Doe',
        'firstname' => 'John',
        'lastname' => 'Doe',
        'email' => '[email protected]',
        'role_id' => 2,
        'uuid' => '3820202',
        'user_id' => 4
    ]);

    $this->assertDatabaseHas('users', [
        'name' => 'John Doe',
        'firstname' => 'John',
        'lastname' => 'Doe',
        'email' => '[email protected]',
        'role_id' => 2,
        'uuid' => '3820202',
        'user_id' => 4
    ]);
});

Try these steps and see if they help resolve the issue. If the problem persists, it might be helpful to compare the configurations between the project that works and the one that doesn't, focusing especially on any differences in the database and environment settings.

jbianchi's avatar

In your Pest.php add the following line:

Please or to participate in this conversation.