Testing forms (form types) in Symfony 3.3 projects

Viewed 81

In a Symfony 3.3 project I try to test this simple form:

class FooFormType extends AbstractType
{
    private $fooService;

    public function __construct(FooService $fooService)
    {
        $this->fooService = $fooService;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'bar',
                EntityType::class,
                [
                    'class' => Bar::class,
                    'choice_label' => 'title',
                    'placeholder' => 'Please select a bar',
                ]
            )
            ->add(
                'baz',
                ChoiceType::class,
                [
                    'choices' => $this->fooService->lorem(),
                ]
            )
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => Foo::class,
            ]
        );
    }
}

I followed the instruction I found at http://symfony.com/doc/current/form/unit_testing.html#testings-types-from-the-service-container to write this (simplified) test:

class FooFormTypeTest extends TypeTestCase
{
    protected function getExtensions()
    {
        $fooServiceDummy = $this->createMock(FooService::class);
        $fooFormType = new FooFormType($fooServiceDummy);

        $managerRegistryDummy = $this->createMock(ManagerRegistry::class);
        $entityFormType = new EntityType($managerRegistryDummy);

        return [
            new PreloadedExtension([$fooFormType, $entityFormType], []),
        ];
    }

    /**
     * @test
     */
    public function submitValidData()
    {
        $form = $this->factory->create(FooFormType::class);
    }
}

Unfortunatelly this exception is thrown:

Symfony\Component\Form\Exception\RuntimeException: Class "AppBundle\Entity\Bar" seems not to be a managed Doctrine entity. Did you forget to map it?

What is the problem here?

0 Answers
Related