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

时间:2018-05-13 16:05:13

标签: 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(),
        ]);

    }

}

4 个答案:

答案 0 :(得分:29)

您必须使用$this->faker->firstName()而不仅仅是$faker->firstName()

答案 1 :(得分:15)

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

$this->setUpFaker();

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

答案 2 :(得分:0)

完成Faker的安装。 包括自动加载文件并创建实例

$faker = Faker\Factory::create();
$faker->firstname()
$faker->lastname()

有关更多信息,visit

答案 3 :(得分:0)

检查种子功能运行情况(Faker $ faker)。