5

I want to unit test the validation on a custom FormTypeInterface.

I have a custom Form Type set up like this:

class HiddenFieldType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', 'text', [
            'constraints' => [
                new NotBlank([
                    'message' => 'hiddenfield-invalid'
                ])
            ]
        ]);
    }

    public function getName()
    {
        return 'hiddenfield';
    }
}

I want to test that the constraint holds by instantiating the form object. From the Symfony documentation, I have come up with this:

public function testValidation()
{
    $formData = [
        'name' => null // blank value
    ];

    $hiddenFieldType = new HiddenFieldType();
    $form = $this->factory->create($hiddenFieldType);

    // submit the data to the form directly
    $form->submit($formData);

    var_dump($form->isValid()); die;
}

// factory is set up as per http://stackoverflow.com/a/27035802/614523
protected function setUp()
{

    parent::setUp();
    $validator = $this->getMock('\Symfony\Component\Validator\ValidatorInterface');
    $validator->method('validate')->will($this->returnValue(new ConstraintViolationList()));
    $formTypeExtension = new FormTypeValidatorExtension($validator);

    $this->factory = Forms::createFormFactoryBuilder()
        ->addExtensions($this->getExtensions())
        ->addExtension(new HttpFoundationExtension())
        ->addTypeExtension($formTypeExtension)
        ->getFormFactory();
}

My current understanding tells me that $form->isValid() should return false here (this is how it is used in the controller and in the documentation, but $form->isValid() always returns true as long as $formData['name'] contains a string.

I have also tried passing the data using a use Symfony\Component\HttpFoundation\Request object:

public function testValidation($userInput, $isValid)
{
    $formData = [
        'name' => 'asdasd'
    ];

    $hiddenFieldType = new HiddenFieldType();
    $form = $this->factory->create($hiddenFieldType);

    // submit the data to the form using the request object
    $request = new Request($getParams = [], $postParams = $formData);
    $form->handleRequest($request);

    var_dump($form->isValid()); die;
}

When I do this $form->isValid() always returns false, where I would expect it to be true whenever $formData['name'] is not null and not an empty string.

What am I doing wrong?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.