Laravel 5.1 具有 "use DatabaseMigrations;" 的 PHPUnit 在访问测试数据库时产生错误

Laravel 5.1 PHPUnit with "use DatabaseMigrations;" Produces Error when Accessing Test DB

我正在学习 Laravel 5.1 的 PHPUnit。我正在使用 "use DatabaseMigrations" 为每个测试迁移测试数据库,这是我在 phpunit.xml:

中设置的
<php>
    ...
    <env name="DB_DATABASE" value="project_test"/>
    ...
</php>

我在检查实例化、工厂等过程中设置了一系列基本测试,但我想检查 UserModel 中的访问器和修改器:

public function getFullNameAttribute()
{
    return $this->first_name . ' ' . $this->last_name;
}

public function getPasswordAttribute($password)
{
    $this->attributes[ 'password' ] = bcrypt($password);
}

但是当访问器测试运行时:

/**
 * A basic check of full name accessor.
 *
 * @return void
 */
public function testCheckFullNameOfUser()
{
    $user = User::all();

    $this->assertEquals($user->first_name . ' ' . $user->last_name, $user->fullname);
}

我收到这个错误:

1) UserTest::testCheckFullNameOfUser
ErrorException: Trying to get property of non-object

这似乎表明数据库尚未迁移,SSHing 到 Homestead 并登录到 MySQL 并检查迁移 table 测试数据库为空,似乎没有迁移发生了。

为了完成这项工作,我在文档中遗漏了什么?我只是复用用户工厂就可以通过,但是我不明白为什么我不能访问测试数据库,是否需要初始迁移?

您收到该错误是因为您的数据库中没有任何用户。

首先,当您 use DatabaseMigrationstests Laravel 中继续并在每次测试之前运行迁移并在每次测试之后执行 "rollback"。这样,您的每个测试都有一个新的数据库,一个测试的剩余数据不会影响后续测试。

这意味着如果您的某个测试期望数据库中有用户,那么您需要在该测试中创建它们。这也解释了为什么你查看时测试数据库中没有任何数据。

其次,User::all() returns 个 collection 用户。如果你想要一个单一的用户,你应该尝试 User::first().

试试这个测试:

public function testCheckFullNameOfUser()
{
    User::create(['first_name'=>'John', 'last_name'=>'Smith']);
    $user = User::first();

    $this->assertEquals('John Smith', $user->fullname);
}