Laravel无法找到用户工厂

时间:2020-10-12 11:25:56

标签: laravel

我正在Laravel中进行一些测试,并且遇到了一个非常持久的错误:InvalidArgumentException: Unable to locate factory for [App\Models\User].

User类和UserFactory都存在,我相信我使用了正确的命名空间。我曾尝试运行composer dump autoload并清除cacheconfig,但这没有用。

我的功能测试:

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class ProjectsTest extends TestCase
{
    use WithFaker, RefreshDatabase;

    /** @test */
    public function only_authenticated_users_can_create_projects()
    {
        $attributes = factory('App\Models\Project')->raw();
        $this->post('/projects', $attributes)->assertRedirect('login');
    }
}

这是ProjectFactory:

<?php

use Faker\Generator as Faker;

$factory->define(App\Models\Project::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence,
        'description' => $faker->paragraph,
        'owner_id' => function () {
            return factory(App\Models\User::class)->create()->id;
        },
    ];
});

这是UserFactory:

<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = User::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
}

1 个答案:

答案 0 :(得分:1)

在您的UserFactory类中,我假设您正在使用Laravel 8。

pd.Series.mask的新方法是

$user = User::factory()->create();

代替原来的方式

$user = factory(User::class)->create();

我认为您在ProjectFactory中混合了Laravel 8和7语法。我建议删除您的ProjectFactory 并使用PHP artisan命令php artisan make:factory ProjectFactory在Laravel 8的基础上重新创建它。 然后您将像这样致电工厂:

$project = Project::factory()->create();

请确保您的Project模型使用hasFactory;特性来使其正常工作。