Skip to content

Unit testing FormType with constructor #6053

Closed
@hackzilla

Description

@hackzilla

This code used to work in Symfony <= 2.7

        $userManager = $this->getMock('Hackzilla\Bundle\TicketBundle\User\UserInterface');
        $form = $this->factory->create(new \Hackzilla\Bundle\TicketBundle\Form\Type\TicketMessageType($userManager));

However in Symfony 3.0, the following error is thrown.

Symfony\Component\Form\Exception\UnexpectedTypeException: Expected argument of type "string", "Hackzilla\Bundle\TicketBundle\Form\Type\TicketMessageType" given

/ticketapp/vendor/hackzilla/ticket-bundle/vendor/symfony/symfony/src/Symfony/Component/Form/FormFactory.php:64
/ticketapp/vendor/hackzilla/ticket-bundle/vendor/symfony/symfony/src/Symfony/Component/Form/FormFactory.php:39
/ticketapp/vendor/hackzilla/ticket-bundle/Tests/Form/Type/TicketMessageTypeTest.php:33

The functionality was changed in this commit. There doesn't seem to be any mention of the above, in any change logs, only that getName was deprecated.

[Form] removed deprecated FormType::getName()

I've been on the hunt for documentation that explains how to do this.

In How to Unit Test your Forms (3.0), the following code appears, but I can't see how it'd work.

        $type = new TestedType();
        $form = $this->factory->create($type);

Whereas it should be passed in as a string.

$form = $this->factory->create('\AppBundle\Form\Type\TestedType');

Though I'm still confused as to how you're supposed to do the above when your type has a constructor.

Closest I have found seems to be:

class TicketMessageTypeTest extends TypeTestCase
{
    protected function getExtensions()
    {
        $userManager = $this->getMock('Hackzilla\Bundle\TicketBundle\User\UserInterface');
        $ticketMessageType = new \Hackzilla\Bundle\TicketBundle\Form\Type\TicketMessageType($userManager);

        return [new PreloadedExtension([
            $ticketMessageType->getBlockPrefix() => $ticketMessageType,
        ], [])];
    }
...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    FormactionableClear and specific issues ready for anyone to take them.good first issueIdeal for your first contribution! (some Symfony experience may be required)hasPRA Pull Request has already been submitted for this issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions