douganmo1121 2017-09-30 12:20
浏览 48
已采纳

Symfony3单元测试表单在无效数据时始终有效

I use Symfony3 and forms. I have a formType and I want to test it. I follow this article : http://symfony.com/doc/current/form/unit_testing.html

My formType is the following :

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Required;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $aOption)
    {

        $builder->add('name', TextType::class, array(
            'constraints' => array(
                new NotBlank(),
                new Length(array('min' => 3)),
            ),
        ))
            ->add('age', IntegerType::class, array(
                'constraints' => array(
                    new GreaterThanOrEqual(array('value' => 18)),
                    new Required()),

            ));
    }
}

The name must have more than 3 chars and the age must be greater than 18. I want to test with phpunit, with invalid data to submit. The age I submut is invalid because it is less than 18, and the name is invalid because it contains 1 char. My test class is the following :

namespace Tests\AppBundle\Controller;

use AppBundle\Form\UserType;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\Form;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class UserTypeTest extends TypeTestCase
{
    private $validator;
    protected function getExtensions()
    {
        $this->validator = $this->createMock(ValidatorInterface::class);
        // use getMock() on PHPUnit 5.3 or below
        // $this->validator = $this->getMock(ValidatorInterface::class);
        $this->validator
            ->method('validate')
            ->will($this->returnValue(new ConstraintViolationList()));
        $this->validator
            ->method('getMetadataFor')
            ->will($this->returnValue(new ClassMetadata(Form::class)));
        return array(
            new ValidatorExtension($this->validator),
        );
    }
    public function testIndex()
    {
        $formData = array(
            'name' => 'a',
            'age'  => '4'
        );
        $formBuilder = $this->factory->createBuilder(UserType::class);
        $form = $formBuilder->getForm();
        $form->submit($formData);
        $this->assertTrue($form->isSynchronized());
        $this->assertFalse($form->isValid());

    }
}

When I want to run the tests with invalid data to submit, I have failure :

./vendor/bin/phpunit tests/AppBundle/Controller/UserTypeTest.php  
Failed asserting that true is false.

Why the form is always valid ?

  • 写回答

1条回答 默认 最新

  • doushenjia8514 2017-09-30 12:23
    关注

    Your form is always valid because your new ConstraintViolationList() is empty.

    I can suggest you to replace your UserTypeTest::getExtensions() method by the following :

    public function getExtensions()
    {
        $extensions = parent::getExtensions();
        $metadataFactory = new FakeMetadataFactory();
        $metadataFactory->addMetadata(new ClassMetadata(  Form::class));
        $validator = $this->createValidator($metadataFactory);
    
        $extensions[] = new CoreExtension();
        $extensions[] = new ValidatorExtension($validator);
    
        return $extensions;
    }
    
    
    protected function createValidator(MetadataFactoryInterface $metadataFactory, array $objectInitializers = array())
    {
        $translator = new IdentityTranslator();
        $translator->setLocale('en');
        $contextFactory = new ExecutionContextFactory($translator);
        $validatorFactory = new ConstraintValidatorFactory();
        return new RecursiveValidator($contextFactory, $metadataFactory, $validatorFactory, $objectInitializers);
    }
    

    With this ValidatorExtension, you should have not empty ConstraintViolationList

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。