Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to undefined method newCollection when using factories with Laravel-Doctrine

I would like to use Model factories, but I get this error:

1) Tests\Factory\UserFactoryTest::testUserCount
Error: Call to undefined method App\Entities\User::newCollection()

C:\Projects\factory_test\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:228
C:\Projects\factory_test\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:178
C:\Projects\factory_test\tests\Factory\UserFactoryTest.php:21

The factory code was copied from the Laravel-Doctrine example project :

$factory->define(App\Entities\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->title,
    ];
});

What do I wrong? Do I need additional configurations, before using factories? Doctrine works perfectly, I only have issue with factory()

The test class looks like this:

class UserFactoryTest extends TestCase {

    private $users = array();

    protected function setUp(): void
    {
        parent::setUp();

        $this->users = factory(User::class, 3)->create();
    }

    // ...

}
like image 372
Iter Ator Avatar asked Dec 15 '25 15:12

Iter Ator


1 Answers

Your setUp() function is using the standard Laravel factory() helper to generate the test data.

Change this to:

protected function setUp(): void
{
    parent::setUp();
    $this->users = entity(User::class, 3)->create();
    //             ^^^^^^
}

The Laravel Doctrine entity() helper method uses a different base class behind the scenes than the standard Laravel factory() helper method.

// Laravel Doctrine
$factory = app('LaravelDoctrine\ORM\Testing\Factory');

Compare to the factory() helper method in the Laravel framework:

// Laravel framework
$factory = app(EloquentFactory::class);
like image 94
Erich Avatar answered Dec 17 '25 06:12

Erich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!