我开始使用 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。但我无法在代码中发现任何问题。我的代码有什么问题,我该如何解决?