Laravel 7 模型工厂为 faker 抛出“InvalidArgumentException:未知格式化程序”异常

问题描述 投票:0回答:2

我开始使用 Laravel 8 构建一个 Web 应用程序。我注意到 Laravel 8 中发生了一些变化,包括模型工厂。现在,我正在使用模型工厂编写单元测试。但是当我使用 faker 伪造字段时,它会抛出错误。

这是我的测试方法。

public function testHasRoleReturnsTrue()
{
    $user = User::factory()->create();
}

如您所见,我现在想做的就是尝试使用工厂创建一个用户。这是我的用户模型工厂类。

<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Foundation\Testing\WithFaker;
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),
        ];
    }
}

正如你所看到的,我正在使用 faker 来伪造值。当我运行测试时,出现以下错误。

InvalidArgumentException: Unknown formatter "name"

/var/www/vendor/fzaninotto/faker/src/Faker/Generator.php:248
/var/www/vendor/fzaninotto/faker/src/Faker/Generator.php:228
/var/www/vendor/fzaninotto/faker/src/Faker/Generator.php:274
/var/www/database/factories/UserFactory.php:28
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:366
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:345
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:329
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php:157
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:334
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:302
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:228

我认为该错误是因为我使用了 faker。但我无法发现代码中的任何问题。我的代码有什么问题以及如何修复它?

laravel faker laravel-8 laravel-factory
2个回答
12
投票

这是因为您在单元测试中使用了它。它正在扩展 PhpUnit 的 TestCase。

当你扩展 Laravel 的 TestCase 时,它应该可以工作。


0
投票

我遇到了同样的问题,这就是我在 Laravel 11 上解决它的方法:在 pest.php 中的 pest 函数中添加“unit”,并使其类似于:

pest()->extend(Tests\TestCase::class)
    ->use(Illuminate\Foundation\Testing\RefreshDatabase::class)
    ->in('Feature', 'Unit');
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.