当我在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');
});
}
}
答案 0 :(得分:8)
问题是你无法在setUpBeforeClass中执行此操作,因为许多内容都在setUp
方法中运行。如果查看this order of run,您会看到setUpBeforeClass
在setUp
方法之前运行,而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;
}
所以你要做的就是用自己的实现创建自己的setUp
和tearDown
方法,如下所示:
protected function setUp()
{
parent::setUp();
// your code goes here
}
protected function tearDown()
{
parent::tearDown();
// your code goes here
}
答案 1 :(得分:2)
对于其他对我使用Capsule工作的其他方法感到好奇的人,这里是代码。这适用于setUpBeforeClass()
和setUp()
。这可能而且应该更抽象,但这是它的要点。
use Illuminate\Database\Capsule\Manager as Capsule;
class DiscussionModelTest extends TestCase
{
/**
* Create the tables this model needs for testing.
*/
public static function setUpBeforeClass()
{
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();
Capsule::schema()->create('discussions', function (Blueprint $table) {
$table->integer('id');
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
Capsule::schema()->create('users', function (Blueprint $table) {
$table->integer('id');
});
// Seed the faux DB
Model::unguard();
User::create([
'id' => 13
]);
Discussion::create([
'id' => 5,
'user_id' => 13
]);
}
}