在使用 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
任何个人或团体,未经允许禁止转载本文:

发表评论
沙发空缺中,还不快抢~