Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.7 Unable to locate factory with name [default] [App\User]

What's going on with Laravel 5.7 Factories? When I run the factory on php artisan tinker it works fine. But when I use it with Unit Tests it throws an error:

Unable to locate factory with name [default] [App\User]

Here's my Unit Test

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use \App\User;

class UserTest extends TestCase
{
    use DatabaseTransactions;

    public function setUp()
    {
        $this->user = factory(User::class, 1)->create()->first();
    }

    /**
     * @test
     */
    public function a_sample_test()
    {
        $this->assertTrue(!empty($this->user));

    }
}

And UserFactory was generated by running php artisan make:factory UserFactory --model=User

This is my factory for User on /database/factories

<?php

use Faker\Generator as Faker;

$factory->define(\App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

I've run to similar questions here on SO, but they all seem to have the same answer to use \App\Model::class instead of App\Model::class.

like image 313
Dexter Bengil Avatar asked Oct 15 '18 04:10

Dexter Bengil


2 Answers

The error is also thrown due to importing the wrong TestCase and not just parent::setUp(); only

-

use PHPUnit\Framework\TestCase; [WRONG: and throws this error]


use Tests\TestCase; [CORRECT]

like image 162
Ayeni TonyOpe Avatar answered Oct 26 '22 22:10

Ayeni TonyOpe


Ohh shoot! parent::setUp() fixed this issue.

public function setUp()
{
    parent::setUp();

    // more codes here
}
like image 28
Dexter Bengil Avatar answered Oct 26 '22 23:10

Dexter Bengil