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

58

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

未定义的变量 $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个回答

112

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

更新1

现在当我们使用WithFaker Trait时,$this->faker将会返回null,为了解决这个问题,请确保首先调用$this->setupFaker()

例如:

class SomeFactory
{
    use WithFaker;

    public function __construct()
    {
        $this->setUpFaker();
    }

}

信用 @Ebi


2
对于后来者,请注意使用WithFaker trait时,$this->faker将返回null。为了解决这个问题,在调用$this->faker之前,您需要调用$this->setupFaker() - Ebi
1
感谢 @Ebi 发现了这个问题。 - Abdel mounaim
2
你需要将 use Illuminate\Foundation\Testing\WithFaker; 添加到你的导入中!为什么大家都忽略了这个重要的部分? - Sliq
2
在 Laravel 8 中,这个过程似乎更加顺畅。只需添加 use WithFaker;,然后 $this->faker 就可以在所有测试中使用了。 - Jason
@Sliq 这已经在 Laravel 测试的默认存根中了。 - Nilpo

41

对于来自2021年的人们。我们不再要求添加

$this->setUpFaker();

您只需要按照被接受的答案中所描述的那样包含该特性。


1
并将 use Illuminate\Foundation\Testing\WithFaker; 添加到您的导入中。 - Sliq

16

完成 Faker 安装之后,包含自动加载文件并创建实例

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

获取更多信息,请访问


0

检查您的种子函数是否运行(Faker $faker)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接