I'm using EntityRepositories as a service in my application. All works fine, but when testing my forms with a TypeTestCase, an EntityManager can't be created for EntityType
form fields because an EntityManager
is being injected instead of a Manager
.
Here is my code, partly based on this answer:
<?php
use App\Entity\Bar;
use App\Entity\Foo;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\EntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Test\TypeTestCase;
class FooType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) // phpcs:ignore
{
$builder->add(
'bar',
EntityType::class,
[
'class' => Bar::class,
'query_builder' => static function (EntityRepository $er) {
return $er->createQueryBuilder('bar');
},
]
);
}
}
final class BarRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Bar::class);
}
}
class FooTypeTest extends TypeTestCase
{
protected function setUp(): void
{
$this->entityManager = DoctrineTestHelper::createTestEntityManager();
// ...
parent::setUp();
}
public function testSubmitValidData()
{
$foo = new Foo();
$form = $this->factory->create(FooType::class, $foo);
}
}
When running this test, I get this error message:
TypeError : Argument 1 passed to BarRepository::__construct() must implement interface Doctrine\Persistence\ManagerRegistry, instance of Doctrine\ORM\EntityManager given, called in vendor/doctrine/orm/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php on line 69
I'm using Symfony 4.4.2, doctrine/doctrine-bundle 1.12.6, doctrine/orm v2.7.0, symfony/phpunit-bridge v5.0.2 and phpunit/phpunit 8.5.2.
Any idea how I can use a TypeTestCase
while using a ServiceEntityRepository
?