Laravel 10.x - A facade root has not been set.解决办法

2024-08-30 13:28:19 浏览数 (5)

今天在laravel单元测试中使用Http请求接口时,报错显示A facade root has not been set.

默认单元测试的代码是这样的

代码语言:php复制
<?php

namespace TestsUnit;

use IlluminateSupportFacadesHttp;
use PHPUnitFrameworkTestCase;
use TestsCreatesApplication;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     */
    public function test_that_true_is_true(): void
    {
        $resp= Http::get('https://b.example.com/login')->json();
        var_dump($resp);
        $this->assertTrue(true);
    }

}

找到解决办法,如下:

代码语言:php复制
<?php

namespace TestsUnit;

use IlluminateContractsConsoleKernel;
use IlluminateSupportFacadesHttp;
use IlluminateFoundationTestingTestCase as BaseTestCase;

class ExampleTest extends BaseTestCase
{
    /**
     * A basic test example.
     */
    public function test_that_true_is_true(): void
    {
        $resp= Http::get('https://b.example.com/login')->json();
        var_dump($resp);
        $this->assertTrue(true);
    }

    public function createApplication()
    {
        // TODO: Implement createApplication() method.
        $app = require __DIR__.'/../bootstrap/app.php';
        $app->make(Kernel::class)->bootstrap();
        return $app;
    }
}

不太优美,感觉不是laravel的风格,于此同时在单元测试目录下发现一个CreatesApplication的trait类,于是修改代码为这样

代码语言:php复制
<?php

namespace TestsUnit;

use IlluminateSupportFacadesHttp;
use IlluminateFoundationTestingTestCase as BaseTestCase;
use TestsCreatesApplication;

class ExampleTest extends BaseTestCase
{
    use CreatesApplication;

    /**
     * A basic test example.
     */
    public function test_that_true_is_true(): void
    {
        $resp= Http::get('https://b.example.com/login')->json();
        var_dump($resp);
        $this->assertTrue(true);
    }
}

emmmm....非常优美,这才是laravel的感觉,再次运行单元测试,完美通过

1 人点赞