Search code examples
laravellaravel-5

Laravel - How to use faker in PHPUnit test?


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

undefined variable $faker.

This is the WithFaker file.

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

    }

}

Solution

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

    Update 1

    Now when we use WithFaker Trait $this->faker will give us null, to get around this make sure to call $this->setupFaker() first.

    e.g.

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

    credit @Ebi