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

2

6

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.

Rabies answered 15/10, 2018 at 4:39 Comment(0)
R
12

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

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

    // more codes here
}
Rabies answered 15/10, 2018 at 4:54 Comment(1)
not fixed me i'm still get same errors. how can i fixed it ?Beitnes
T
15

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]

Trocki answered 21/1, 2020 at 8:38 Comment(1)
With Laravel 7 doing unit testing, this is the only thing that worked for me. But this is the default class import if you create unit test using command line.Esurient
R
12

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

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

    // more codes here
}
Rabies answered 15/10, 2018 at 4:54 Comment(1)
not fixed me i'm still get same errors. how can i fixed it ?Beitnes

© 2022 - 2024 — McMap. All rights reserved.