'Is Laravel 8 Testing with a database broken out of the box
I have a new Laravel 8 install, running on docker with sail. Everything seems to run fine, but tests that use any configuration seem to be broken. For example a simple test that pulls a user out of the database fails.
I am using the default phpunit.xml, and I added a .env.testing, which is just a copy of .env
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Added a quick test to the unit ExampleTest.php
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$user = User::find(1);
$this->assertInstanceOf(User::class, $user);
}
Run sail php artisan test Tests: 1 failed, 16 passed Time: 2.70s
• Tests\Unit\ExampleTest > basic test
Error
Call to a member function connection() on null
at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1493
1489▕ * @return \Illuminate\Database\Connection
1490▕ */
1491▕ public static function resolveConnection($connection = null)
1492▕ {
➜ 1493▕ return static::$resolver->connection($connection);
1494▕ }
1495▕
1496▕ /**
1497▕ * Get the connection resolver instance.
I have a number of laravel apps that run these exact same test in previous versions of Laravel. What am I missing?
Thanks,
Solution 1:[1]
You sure you're using a fresh phpunit.xml and .env?
I found backupGlobals="false" backupStaticAttributes="false" was killing some vars at $_ENV and $_SERVER, and a nasty component was reading variables from there.
What I did was expose .env and phpunit.xml to phpunit inside a tests and test its values. Found out that you cannot read with env('key') the data at /.env (phpunit environment variables are different of what you configure inside .env and phpunit.xml), which apply only to the tested application.
Installing a fresh version of Laravel 8 on a new project and comparing my tree with the fresh one showed me I was also missing some .env definitions and that had an overbloated phpunit.xml file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Obsidian |
