Tho*_*eia 4 php phpunit laravel
我创建了以下单元测试:
<?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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到:
SQLSTATE[HY000]: General error: 1 no such table: users
Run Code Online (Sandbox Code Playgroud)
但是,当我打开时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,
}
Run Code Online (Sandbox Code Playgroud)
很明显,工厂在工作,桌子存在。
这里发生了什么?
谢谢,
Gio*_*i S 14
当您以一种或另一种方式运行测试时,您将需要迁移数据库。
一种常见的方法是利用RefreshDatabase特征。
<?php
namespace Tests\Unit;
use Tests\TestCase;
use App\User;
use App\Organization;
use Illuminate\Foundation\Testing\RefreshDatabase;
class UserTest extends TestCase
{
use RefreshDatabase;
public function testUserHasOwnedOrganization()
{
$user = factory(User::class)->create();
$organization = factory(Organization::class)->create([
'organizer_id' => $user->id,
]);
$this->assertContains($organization, $user->owned_organizations);
}
}
Run Code Online (Sandbox Code Playgroud)
看看能不能帮到你。
您可以在此处找到有关它的更多信息:https : //laravel.com/docs/7.x/database-testing
| 归档时间: |
|
| 查看次数: |
4771 次 |
| 最近记录: |