使用带有 Laravel-Doctrine 的工厂时调用未定义的方法 newCollection

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

我想使用 Model factories,但出现此错误:

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

工厂代码复制自 Laravel-Doctrine example project :

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

我做错了什么?在使用工厂之前,我是否需要额外的配置? Doctrine 工作得很好,我只有 factory()

有问题

测试 class 看起来像这样:

class UserFactoryTest extends TestCase {

    private $users = array();

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

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

    // ...

}

您的 setUp() 函数正在使用标准 Laravel factory() 帮助程序生成测试数据。

将此更改为:

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

Laravel Doctrine entity() helper method 在幕后使用了与标准 Laravel factory() 辅助方法不同的基础 class。

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

与Laravel框架中的factory() helper method比较:

// Laravel framework
$factory = app(EloquentFactory::class);