首页 > 解决方案 > 如何将 Doctrine Repositories 注入 Symfony 3.4 测试用例

问题描述

我一直在遵循https://www.tomasvotruba.cz/blog/2017/10/16/how-to-use-repository-with-doctrine-as-service-in-symfony/上的指示来打开我的存储库到可以注入我的测试的服务中。这是我到目前为止所拥有的:

我的存储库:

<?php
declare(strict_types=1);

namespace OpenCFP\Domain\Repository;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use OpenCFP\Domain\Entity\Airport;

final class AirportRepository
{
    /**
     * @var EntityRepository
     */
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(Airport::class);
    }
}

我的实体

<?php
declare(strict_types=1);
namespace OpenCFP\Domain\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="airports")
 */
final class Airport
{
    /**
     * @ORM\@Id
     * @ORM\Column(type="string", length=3)
     */
    private $code;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $country;
}

这是我services.yml按照我找到的说明添加到文件中的内容

OpenCFP\Domain\Repository\:
  public: true
  resource: '%kernel.project_dir%/src/Domain/Repository/*'

我根据我在这里找到的方向将以下代码添加到setUp()我的测试方法中

$kernel = self::bootKernel();
$this->airport = $kernel->getContainer()->get(AirportRepository::class);

当我运行测试时,我收到以下错误消息:

Symfony\Component\DependencyInjection\Exception\RuntimeException:无法自动装配服务“OpenCFP\Domain\Repository\AirportRepository”:方法“__construct()”的参数“$entityManager”引用接口“Doctrine\ORM\EntityManagerInterface”,但不存在此类服务。它不能自动注册,因为它来自不同的根命名空间。

标签: phpsymfonytestingdoctrine-ormdoctrine

解决方案


推荐阅读