Laravel - 如何在PHPUnit测试中使用faker?

jim*_*o99 24 laravel laravel-5

我在运行测试时给出了这个错误:

未定义的变量$ faker.

这是WithFaker文件.

https://github.com/laravel/framework/blob/5.5/src/Illuminate/Foundation/Testing/WithFaker.php

<?php

namespace Tests\Unit;

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

class LoginTest extends TestCase
{

    use WithFaker;

    /**
     * A basic test example.
     *
     * @return void
     */

    /** @test */
    public function test_example()
    {

        $user = User::create([
            'username' => $faker->firstName(),
        ]);

    }

}
Run Code Online (Sandbox Code Playgroud)

小智 43

你不仅要使用$this->faker->firstName()$faker->firstName()

  • 对于稍后接触到这一点的人,请注意,通过使用 WithFaker 特征,您将在 `$this-&gt;faker` 上收到 null。要处理这个问题,您需要在调用`$this-&gt;faker`之前调用`$this-&gt;setupFaker()`。 (2认同)
  • 并且您需要将 `use Illuminate\Foundation\Testing\WithFaker;` 添加到您的导入中!为什么大家都忽略了这个重要的部分呢? (2认同)
  • 使用 Laravel 8,这似乎更加顺利。只需添加“use WithFaker;”,“$this-&gt;faker”现在可用于所有测试。 (2认同)

Mar*_*sen 19

对于从 2021 年来到这里的任何人。我们不再需要添加

$this->setUpFaker();
Run Code Online (Sandbox Code Playgroud)

您只需要包含已接受答案中描述的特征。


Jay*_*min 10

一旦你完成了 Faker 的安装。包含自动加载文件并创建实例

$faker = \Faker\Factory::create();
$faker->firstname()
$faker->lastname()
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请访问