3

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();
    }

    // ...

}
Iter Ator
  • 8,226
  • 20
  • 73
  • 164
  • It would seem that `$factory` in your case is still using Eloquent. Reading [this article](http://www.laraveldoctrine.org/docs/current/orm/testing) explains that it should be an instance of `LaravelDoctrine\ORM\Testing\Factory` as long as the factory file is located in `database/factories`. – leek Feb 04 '20 at 19:27
  • `$factory` is an instance of `Illuminate\Database\Eloquent\Factory`. But I don't understand why, because my Facory class is located in `database/factories` – Iter Ator Feb 04 '20 at 20:02
  • I would double check that you have gone through all of the setup steps located [here](http://www.laraveldoctrine.org/docs/1.4/orm/installation), specifically the steps involving the ServiceProvider and configuration publishing. – leek Feb 05 '20 at 14:50
  • @leek I tried that, but I still get that error – Iter Ator Feb 14 '20 at 19:15
  • try `$this->users = entity(User::class, 3)->create();` in your `setUp` function instead of `factory()` – Erich Feb 14 '20 at 19:56

1 Answers1

4

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);
Erich
  • 2,408
  • 18
  • 40