前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Laravel 10.x - A facade root has not been set.解决办法

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

原创
作者头像
用砖头敲代码
发布2024-08-30 13:28:19
发布2024-08-30 13:28:19
1480
举报
文章被收录于专栏:用砖头敲代码用砖头敲代码

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

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

代码语言:php
复制
<?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
复制
<?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
复制
<?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的感觉,再次运行单元测试,完美通过

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档