Laravel 5.5 PHPunit测试 - "尚未设置外观根".

Jus*_*ony 5 phpunit facade laravel laravel-5 laravel-5.5

当我对它进行try/catch时DB::Connection()->getPdo();,我得到错误没有设置外观根.Schema在我尝试添加try/catch之前,我相信它也发生在外墙上.当然,测试目录在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');
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*łek 10

问题是你不能在setUpBeforeClass中这样做,因为很多东西都是在setUp方法中运行的.如果你看一下这个运行顺序,你会看到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;
}
Run Code Online (Sandbox Code Playgroud)

所以,你应该做的是创造自己setUptearDown与自己的实现这样的方法:

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

protected function tearDown()
{
   parent::tearDown();
   // your code goes here
}
Run Code Online (Sandbox Code Playgroud)


DEV*_*nça 10

我在这里得到答案

\n

您应该\xe2\x80\x99t,因为功能测试将扩展测试目录中的 TestCase 类,而不是 PHPUnit\xe2\x80\x99s。

\n

消除:

\n
use PHPUnit\\Framework\\TestCase;\n
Run Code Online (Sandbox Code Playgroud)\n

并将其替换为:

\n
use Tests\\TestCase;\n
Run Code Online (Sandbox Code Playgroud)\n