我想在自定义FormTypeInterface
上对验证进行单元测试。
我有一个自定义表单类型设置如下:
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';
}
}
我想通过实例化表单对象来测试约束是否成立。从Symfony documentation开始,我想出了这个:
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();
}
我目前的理解告诉我$form->isValid()
应该在此返回false
(这是在控制器和documentation中使用的方式,但$form->isValid()
始终返回{ {1}}只要true
包含字符串。
我还尝试使用$formData['name']
对象传递数据:
use Symfony\Component\HttpFoundation\Request
当我这样做时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;
}
总是返回false,只要$form->isValid()
不为空而且不是空字符串,我希望它为true
。
我做错了什么?