解决 Laravel 单元测试报错:A facade root has not been set
source link: https://qq52o.me/2802.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
在使用 Laravel 写单元测试时,直接复制了默认的文件:tests/Unit/ExampleTest.php
。
而在测试对象中使用到了 Facades 相关的语法,执行 phpunit
时报错:
RuntimeException: A facade root has not been set.
/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:258
此问题的原因是继承了错误的基类,默认文件 tests/Unit/ExampleTest.php
中:
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$this->assertTrue(true);
}
}
继承的是 PHPUnit\Framework\TestCase
,而我们应该继承 tests/TestCase.php
中的 Tests\TestCase
。
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
}
实际上应该复制 tests/Feature/ExampleTest.php
作为模板文件,就不会遇到这个问题了。
除了复制之外,也可以直接在命令行中直接运行:
php artisan make:test FooTest
将会为你创建 tests/Feature/FooTest.php
文件,而加上 --unit
参数,则是在 tests/Unit
中创建文件。
php artisan make:test BarTest --unit
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK