gpt4 book ai didi

php - 在 Laravel 中运行测试时无法找到 [App\Models\User] 的工厂

转载 作者:行者123 更新时间:2023-12-04 07:25:50 25 4
gpt4 key购买 nike

我正在尝试使用 Laravel 中的测试来测试我的应用程序。但是我有一个错误,每当我使用 php artisan test 运行测试时,它总是说 Unable to locate factory for [App\Models\User] .我不明白为什么会这样
这是我的测试代码:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

class Fish extends TestCase
{
/** @test */
public function test_authenticated_users_can_access_home()
{
$user = factory(User::class)->create();
$this->actingAs($user);

$response = $this->get('/home')->assertOk();
}
}
这是我的模型:
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
use HasFactory, Notifiable;

...
用户工厂
<?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),
];
}

...
}

任何帮助将不胜感激,谢谢
对不起,我的英语不好

最佳答案

从您的 UserFactory 类中,我假设您使用的是 Laravel 8。
Laravel 8 中调用工厂的新方法是

$user = User::factory()->create();
而不是旧方式
$user = factory(User::class)->create();
我认为您在 ProjectFactory 中混合了 Laravel 8 和 7 语法。我建议删除您的 ProjectFactory 并使用 PHP artisan 命令在 Laravel 8 基础上重新创建它: php artisan make:factory ProjectFactory .然后你会像这样调用工厂:
$project = Project::factory()->create();
确保您的项目模型使用 hasFactory;特性使其起作用。

关于php - 在 Laravel 中运行测试时无法找到 [App\Models\User] 的工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68220402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com