MENU

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

• August 21, 2024 • 教程

今天在laravel单元测试中使用Http请求接口时,报错显示A facade root has not been set.
2024-08-21T06:37:54.png
默认单元测试的代码是这样的

<?php

namespace Tests\Unit;

use Illuminate\Support\Facades\Http;
use PHPUnit\Framework\TestCase;
use Tests\CreatesApplication;

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

namespace Tests\Unit;

use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Http;
use Illuminate\Foundation\Testing\TestCase 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

namespace Tests\Unit;

use Illuminate\Support\Facades\Http;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Tests\CreatesApplication;

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的感觉,再次运行单元测试,完美通过
2024-08-21T06:45:14.png

Archives QR Code
QR Code for this page
Tipping QR Code