Laravel 5.7 无法找到名称为 [default] 的工厂 [App\User]
Laravel 5.7 Unable to locate factory with name [default] [App\User]
Laravel 5.7 工厂发生了什么事?当我 运行 php artisan tinker
上的工厂时,它工作正常。但是当我将它与单元测试一起使用时,它会抛出一个错误:
Unable to locate factory with name [default] [App\User]
这是我的单元测试
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use \App\User;
class UserTest extends TestCase
{
use DatabaseTransactions;
public function setUp()
{
$this->user = factory(User::class, 1)->create()->first();
}
/**
* @test
*/
public function a_sample_test()
{
$this->assertTrue(!empty($this->user));
}
}
而UserFactory
是由运行ning生成的
php artisan make:factory UserFactory --model=User
这是我在 /database/factories
上的用户工厂
<?php
use Faker\Generator as Faker;
$factory->define(\App\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => bcrypt('secret'),
'remember_token' => str_random(10),
];
});
我在 SO 上 运行 有类似的问题,但他们似乎都有相同的答案使用 \App\Model::class
而不是 App\Model::class
。
哦拍! parent::setUp()
修复了这个问题。
public function setUp()
{
parent::setUp();
// more codes here
}
同样由于导入错误TestCase而抛出错误] 而不仅仅是 parent::setUp();
只有
-
use PHPUnit\Framework\TestCase;
[WRONG: 并引发此错误]
use Tests\TestCase;
[正确]
Laravel 5.7 工厂发生了什么事?当我 运行 php artisan tinker
上的工厂时,它工作正常。但是当我将它与单元测试一起使用时,它会抛出一个错误:
Unable to locate factory with name [default] [App\User]
这是我的单元测试
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use \App\User;
class UserTest extends TestCase
{
use DatabaseTransactions;
public function setUp()
{
$this->user = factory(User::class, 1)->create()->first();
}
/**
* @test
*/
public function a_sample_test()
{
$this->assertTrue(!empty($this->user));
}
}
而UserFactory
是由运行ning生成的
php artisan make:factory UserFactory --model=User
这是我在 /database/factories
上的用户工厂<?php
use Faker\Generator as Faker;
$factory->define(\App\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => bcrypt('secret'),
'remember_token' => str_random(10),
];
});
我在 SO 上 运行 有类似的问题,但他们似乎都有相同的答案使用 \App\Model::class
而不是 App\Model::class
。
哦拍! parent::setUp()
修复了这个问题。
public function setUp()
{
parent::setUp();
// more codes here
}
同样由于导入错误TestCase而抛出错误] 而不仅仅是 parent::setUp();
只有
-
use PHPUnit\Framework\TestCase;
[WRONG: 并引发此错误]
use Tests\TestCase;
[正确]