Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(),         ]);      }  } 
like image 207
jimmyjoeo99 Avatar asked May 13 '18 16:05

jimmyjoeo99


People also ask

What is the use of Faker in Laravel?

Faker is a PHP package that generates dummy data for testing. With Faker you can generate mass amount of testing data as you needed. Faker comes preinstalled in Laravel framework. You can also use Faker in other frameworks or your own native PHP websites.

What is mockery Laravel?

When testing Laravel applications, you may wish to "mock" certain aspects of your application so they are not actually executed during a given test. For example, when testing a controller that dispatches an event, you may wish to mock the event listeners so they are not actually executed during the test.

What should I unit test in Laravel?

Unit tests are tests that focus on a very small, isolated portion of your code. In fact, most unit tests probably focus on a single method. Tests within your "Unit" test directory do not boot your Laravel application and therefore are unable to access your application's database or other framework services.


2 Answers

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

like image 91
Abdel mounaim Avatar answered Oct 07 '22 15:10

Abdel mounaim


For anyone coming here from 2021. We no longer require the addition of

$this->setUpFaker(); 

You only need to include the trait as described in the accepted answer.

like image 33
Marcus Christiansen Avatar answered Oct 07 '22 15:10

Marcus Christiansen