dimanche 1 décembre 2019

How to inject Doctrine Repositories into Symfony 3.4 test cases

I've been following the directions at https://www.tomasvotruba.cz/blog/2017/10/16/how-to-use-repository-with-doctrine-as-service-in-symfony/ to turn my repositories into services that can be injected into my tests. Here's what I have so far:

My repository:

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

My entity

<?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;
}

Here's what I added to my services.yml file as per the instructions I found

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

I added the following code to the setUp() method of my test based on directions I found here

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

When I run the test I get the following error message:

Symfony\Component\DependencyInjection\Exception\RuntimeException : Cannot autowire service "OpenCFP\Domain\Repository\AirportRepository": argument "$entityManager" of method "__construct()" references interface "Doctrine\ORM\EntityManagerInterface" but no such service exists. It cannot be auto-registered because it is from a different root namespace.

Aucun commentaire:

Enregistrer un commentaire