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.

Dexter Bengil
  • 5,995
  • 6
  • 35
  • 54

2 Answers2

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]

Ayeni TonyOpe
  • 1,651
  • 2
  • 12
  • 6
  • 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. – Mycodingproject Jan 02 '21 at 18:39
12

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

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

    // more codes here
}
Dexter Bengil
  • 5,995
  • 6
  • 35
  • 54