【问题标题】:Laravel - How to use faker in PHPUnit test?Laravel - 如何在 PHPUnit 测试中使用 faker?
【发布时间】:2018-10-23 09:20:53
【问题描述】:

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

未定义的变量 $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(),
        ]);

    }

}

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:

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

    更新 1

    现在,当我们使用WithFaker 时,Trait $this-&gt;faker 将给我们null,要解决这个问题,请务必先致电$this-&gt;setupFaker()

    例如

    class SomeFactory
    {
        use WithFaker;
    
        public function __construct()
        {
            $this->setUpFaker();
        }
    
    }
    

    信用@Ebi

    【讨论】:

    • 对于那些稍后来这里的人,请注意,通过使用 WithFaker 特征,您将在 $this-&gt;faker 上收到 null。要处理此问题,您需要先调用$this-&gt;setupFaker(),然后再调用$this-&gt;faker
    • 感谢@Ebi 的现场
    • 并且您需要将use Illuminate\Foundation\Testing\WithFaker; 添加到您的导入中!为什么大家都忽略了这个重要的部分?
    【解决方案2】:

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

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

    更多信息visit

    【讨论】:

      【解决方案3】:

      检查你的种子函数运行(Faker $faker)。

      【讨论】:

        【解决方案4】:

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

        $this->setUpFaker();
        

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

        【讨论】:

        • 并将use Illuminate\Foundation\Testing\WithFaker; 添加到您的导入中
        猜你喜欢
        • 2021-01-21
        • 1970-01-01
        • 2016-12-31
        • 2019-10-12
        • 1970-01-01
        • 2018-09-05
        • 2019-09-07
        • 2014-09-11
        • 2015-01-24
        相关资源
        最近更新 更多