Laravel单元测试提示A facade root has not been set

2021-03-08 21:15:12 查看 2539 回复 0

在集成单元测试 tests/Unit 时遇到如下报错:

RuntimeException: A facade root has not been set.

/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:258
254▕     {
255▕         $instance = static::getFacadeRoot();
256▕ 
257▕         if (! $instance) {
 258▕             throw new RuntimeException('A facade root has not been set.');
 259▕         }
 260▕ 
 261▕         return $instance->$method(...$args);
 262▕     }

修改 use PHPUnit\Framework\TestCase; 为 use Tests\TestCase;

或者 use CreatesApplication 这个 trait

原因见原帖:Laravel 6/7 testing: A facade root has not been set

解决在单元测试中无法使用:Redis,DB,Config,Route 等 Facade 的问题。