我创建了以下单元测试:
<?php
namespace Tests\Unit;
use Tests\TestCase;
use App\User;
use App\Organization;
class UserTest extends TestCase
{
public function testUserHasOwnedOrganization()
{
$user = factory(User::class)->create();
$organization = factory(Organization::class)->create([
'organizer_id' => $user->id,
]);
$this->assertContains($organization, $user->owned_organizations);
}
}
当我运行它时,我得到:
SQLSTATE[HY000]: General error: 1 no such table: users
However, when I open up php artisan tinker
:
>>> factory(App\User::class)->create()
=> App\User {#3048
name: "Margret Armstrong",
email: "shanel.cormier@example.net",
email_verified_at: "2020-05-18 01:22:30",
updated_at: "2020-05-18 01:22:30",
created_at: "2020-05-18 01:22:30",
id: 1,
}
显然工厂在工作并且桌子已经存在。
这里发生了什么?
谢谢,
一种或另一种方式运行测试时,您将需要迁移数据库。
A common way is to utilize the
RefreshDatabase
trait.看看是否对您有帮助。
You can find more information about it here: https://laravel.com/docs/7.x/database-testing