18

解决 Laravel 单元测试报错:A facade root has not been set

 2 years ago
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.
neoserver,ios ssh client

解决 Laravel 单元测试报错:A facade root has not been set

后端开发 / 2022年2月9日 / 0 条评论
laravel-phpunit.png

在使用 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
沈唁志 任何个人或团体,未经允许禁止转载本文:《解决 Laravel 单元测试报错:A facade root has not been set》,谢谢合作!

如果给您解决燃眉之急或带来些许明朗,您可以打赏一杯咖啡或一杯香茗

LaravelPHPUnit

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK