1

I'm trying to test a model I've created, and I'm getting the error:

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

Here's what my very simple model looks like:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function incidents()
    {
        return $this->hasMany(Incident::class);
    }
}

here's the factory:

<?php

$factory->define(\App\Company::class, function () {
    return [
        'name' => 'ACME Company'
    ];
});

and the setup method in my unit test that's throwing the error:

<?php

use Illuminate\Foundation\Testing\DatabaseMigrations;

class CompanyModelTest extends TestCase
{
    use DatabaseMigrations;

    public function setUp()
    {
        factory(\App\Company::class)->create();
    }

When I run the test I get this:

laradock@63912b4222e6:/var/www/laravel$ vendor/bin/phpunit
PHPUnit 5.5.6 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 528 ms, Memory: 4.00MB

There was 1 error:

1) CompanyModelTest::testCompanyName
InvalidArgumentException: Unable to locate factory with name [default] [App\Company].

/var/www/laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:126
/var/www/laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:2280
/var/www/laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:139
/var/www/laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:106
/var/www/laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:84
/var/www/laravel/tests/CompanyModelTest.php:13

So far I've tried the suggestions on this other Stackoverflow question about the same error, and also this one.

I've tried moving my new factory into the ModelFactory.php file that's there by default and I've tried using defineAs() instead of define.

I've cleared the cache and run composer dump-autoload as suggested in other posts around the web.

I've dumped out the contents of FactoryBuilder::definitions which is empty, and that's what's causing the exception to be thrown.

I've confirmed that none of the factory files in database\factories directory are being called with debug code & a line that would cause a parse error.

Why aren't those files being called as per the documentation?

Community
  • 1
  • 1
Stuart Grimshaw
  • 1,541
  • 1
  • 18
  • 41

1 Answers1

1

In my situation the TestCase was wrong class.

class CompanyModelTest extends TestCase

Which TestCase do you extend? I had

use PHPUnit\Framework\TestCase;

Instead of Laravel's own. Now it is working!

use Tests\TestCase;

Make sure you extend the correct TestCase class.

Mcload
  • 288
  • 8
  • 18