Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Laravel InvalidArgumentException: Unable to locate factory with name [default] [App\User]

I have a setup function in a test which does the following

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

ofcourse I used "use App\User;" at the very top.

This is my model factory

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

When runnning phpunit i get the error

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

HOWEVER: If I go to php artisan tinker an run

factory(User::class)->create();

it works ... I tried App\User::class and other stuff and even putting it inside the test directly instead of the setUp method. The weird part is that another factory within the same file is working.

like image 828
Frnak Avatar asked Oct 31 '16 13:10

Frnak


2 Answers

I found the solution: I needed to call parent setUp function

function setUp()
{
    parent::setUp(); // was missing

    $this->user = factory(App\User::class)->create();
}
like image 173
Frnak Avatar answered Sep 27 '22 22:09

Frnak


The main reason why you always get

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

is because your app were unable to locate the User model.

If you call it make sure you do:

factory(\App\User::class)->create();

I ran into this problem when I'm doing my unit testing.

I hope it helps.

like image 20
Tami Pangadil Avatar answered Sep 27 '22 20:09

Tami Pangadil