今天在laravel单元测试中使用Http请求接口时,报错显示A facade root has not been set.
默认单元测试的代码是这样的
<?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的感觉,再次运行单元测试,完美通过