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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50318048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:42:53  来源:igfitidea点击:

Laravel - How to use faker in PHPUnit test?

laravellaravel-5

提问by jimmyjoeo99

It's giving me this error when I run the test:

当我运行测试时,它给了我这个错误:

undefined variable $faker.

未定义的变量 $faker。

This is the WithFaker file.

这是 WithFaker 文件。

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

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

    }

}

回答by Abdel mounaim

You have to use $this->faker->firstName()not just $faker->firstName()

你必须使用$this->faker->firstName()不只是$faker->firstName()

回答by Jaymin

once you completed installation of Faker. include autoload file and create instance

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

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

For more information visit

欲了解更多信息,请访问