InvalidArgumentException: Unable To Locate Factory With Name [default] - Laravel, Faker, Phpunit

- 1 answer

Since I am developing package, so I put my factories to custom path like this:

-- app

-- packages





----------------- PageModelFactory.php


this is how i load factory in my service provider (I already make sure the path is correct by clicking it on phpstorm):

function boot()
 Factory::construct($this->app->make(\Faker\Generator::class), __DIR__."/../database/factories");

this is my page model factory (I already made sure this file was really loaded):


/** @var \Illuminate\Database\Eloquent\Factory $factory */
use Mockizart\Blog\Dodols\PageModel;
use Faker\Generator as Faker;

$factory->define(PageModel::class, function (Faker $faker) {
    return [
        'name' => "retretre",
        'slug' => "retretret",
        'type' => 0,
        'category' => 0,
        'tags' => "",
        'content' => "",

and this is my script test :

use Mockizart\Blog\Dodols\PageModel;
/** @test */
public function edit_page()
   dd(PageModel::find(1)); <-- this return was NULL so I think my class and namespace does exist.

   factory(PageModel::class)->make(); <-- this cause error "unable to locate factory......"
   $response = $this->get('/blog/page/edit/15');


so if you are using orchestra\Testbench, the correct way to load custom factories is in the setUp() method of your Test class or TestCase NOT in your Service Provider.

the code would be like this:

class TestCase extends \Orchestra\Testbench\TestCase
   public function setUp(): void
     // additional setup
     $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');

   protected function getPackageProviders($app)
       return BlogServiceProvider::class;