Skip to content

How to import and use Faker in Laravel unit testing using PHPUnit

If you think the Faker class can help you in testing Laravel then add this line of code into your import section:

use Illuminate\Foundation\Testing\WithFaker;

Inside your class add:

use WithFaker;

Now you can use it! It wasn’t easy?

$this->faker

A simple example of using Faker in your test:

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;  // step one

class CodePasteTest extends TestCase
{
    use WithFaker;  // step two
    public function testCodePasteNameTest()
    {
    	$randomName = $this->faker->name; // step three
        $this->assertNotEquals($randomName, 'Morteza');
    }
}

2 thoughts on “How to import and use Faker in Laravel unit testing using PHPUnit”

Leave a Reply

Your email address will not be published. Required fields are marked *