Lumen-framework: [5.7] Eloquent Models have no ConnectionResolver

Created on 14 Sep 2018  路  4Comments  路  Source: laravel/lumen-framework

  • Lumen Version: 5.7.0
  • PHP Version: 7.2.9 cli

Description:

When running tests in Lumen 5.7, the Eloquent models do not get an ConnectionResolver, and thus no connection.

This produces the following error:

1) Tests\Feature\AccessLoggerTest::it_logs_requests_with_a_user
Error: Call to a member function connection() on null

/path/to/code/vendor/illuminate/database/Eloquent/Model.php:1234
/path/to/code/vendor/illuminate/database/Eloquent/Model.php:1200
/path/to/code/vendor/illuminate/database/Eloquent/Model.php:1030
/path/to/code/vendor/illuminate/database/Eloquent/Model.php:945
/path/to/code/vendor/illuminate/database/Eloquent/Model.php:983
/path/to/code/vendor/illuminate/database/Eloquent/FactoryBuilder.php:203
/path/to/code/vendor/illuminate/support/Collection.php:407
/path/to/code/vendor/illuminate/database/Eloquent/FactoryBuilder.php:207
/path/to/code/vendor/illuminate/database/Eloquent/FactoryBuilder.php:181
/path/to/code/tests/Feature/AccessLoggerTest.php:42

Steps To Reproduce:

  1. Inside a test, do an eloquent call. Mine was $user = factory(ApiUser::class)->create();
  2. Make sure your phpunit.xml set's your env variables correctly (I copied mine from the master of this repo). Make sure both APP_ENV and DB_CONNECTION are set to testing.
  3. Make sure you enable $app->withEloquent() in bootstrap/app.php. Enabling or disabling $app->withFacades() has no effect, so you can leave that one disabled.
  4. Run vendor/bin/phpunit
  5. Experience the above error

Workaround

Override your Eloquent models constructor and add the following:

public function __construct(array $attributes = [])
{
    $resolver = app('Illuminate\Database\ConnectionResolverInterface');

    $this->setConnectionResolver($resolver);

    parent::__construct($attributes);
}

Updated workaround

Add the following method to your BaseTest. You don't need to change the Models.

public function refreshApplication()
{
    parent::refreshApplication();

    $this->app->boot();
}

Most helpful comment

Also experiencing this issue and the updated workaround works for me.

All 4 comments

Also experiencing this issue and the updated workaround works for me.

I updated from 5.6 to 5.7 and also got this error. The workaround, put into tests/TestCase.php, fixed the issue. Thanks @georgeboot !
I hope this'll be officially integrated soon.

I made a pull request to fix this issue.

Fixed in #809

Was this page helpful?
0 / 5 - 0 ratings