getPdo();进行try/catch时,出现错误。尚未设置外观根。 ,我相信在尝试添加try/catch之前,Schema外观也会发生这种情况。当然,te-6ren">
gpt4 book ai didi

Laravel 5.5 PHPunit测试- "A facade root has not been set."

转载 作者:行者123 更新时间:2023-12-04 16:50:52 24 4
gpt4 key购买 nike

当我对DB::Connection()->getPdo();进行try/catch时,出现错误。尚未设置外观根。 ,我相信在尝试添加try/catch之前,Schema外观也会发生这种情况。当然,tests目录位于app目录之外,我觉得它与此有关,但是我没有成功地将其弄清楚。

这是发生这种情况的测试类:

<?php

namespace Tests\Models;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use App\Models\Discussion;
use App\User;
use Business\Database\Model;
use Illuminate\Database\Schema\Blueprint;
use Tests\TestCase;

class DiscussionModelTest extends TestCase
{
/**
* Create the tables this model needs for testing.
*/
public static function setUpBeforeClass()
{
try {
DB::connection()->getPdo();
} catch(\Exception $e) {
die($e->getMessage());
}

Schema::create('discussions', function (Blueprint $table) {
$table->integer('id');
$table->integer('user_id');

$table->foreign('user_id')->references('id')->on('users');
});

Schema::create('users', function (Blueprint $table) {
$table->integer('id');
});
}
}

最佳答案

问题是您无法在setUpBeforeClass中执行此操作,因为许多事情都是在setUp方法中运行的。如果查看this order of run,您将看到setUpBeforeClasssetUp方法之前运行,并且TestCase类在setUp方法中做了很多事情。看起来像这样:

protected function setUp()
{
if (! $this->app) {
$this->refreshApplication();
}

$this->setUpTraits();

foreach ($this->afterApplicationCreatedCallbacks as $callback) {
call_user_func($callback);
}

Facade::clearResolvedInstances();

Model::setEventDispatcher($this->app['events']);

$this->setUpHasRun = true;
}

因此,您应该使用自己的实现创建自己的 setUptearDown方法,如下所示:
protected function setUp()
{
parent::setUp();
// your code goes here
}

protected function tearDown()
{
parent::tearDown();
// your code goes here
}

关于Laravel 5.5 PHPunit测试- "A facade root has not been set.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46452753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com