当单元测试带有dateType字段的表单时,我的表单测试将始终为该字段返回null。
public function testSubmitValidSearchFormData()
{
// Arrange
$date = new \DateTime('tomorrow');
$formData = array(
'date' => $date,
// some other fields
);
$object = new SearchModel();
$object
->setDate($formData['date'])
// set some more fields
// Act
$form = $this->factory->create(SearchType::class);
$form->submit($formData);
// Assert
$this->assertTrue($form->isSynchronized());
$this->assertEquals($object, $form->getData()); // fails, because of field 'date'
// some more tests...
}
SearchType.php:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// other fields
// ...
->add('date', DateType::class)
->add('save', SubmitType::class, [
'label' => 'Finden',
'attr' => ['formnovalidate' => true]
]);
return $builder;
}
任何想法,为什么会这样?我的TestClass不包含任何其他方法。所有其他字段都可以正常工作。
答案 0 :(得分:0)
这不仅仅是关于DateType
:submit
方法不处理对象,如果提供了对象,则会将此类字段设置为null
。在使用此方法之前,您必须将它们转换为数组。你必须遵循这个模式:
[
'attribute_1' => 'value_1',
'attribute_2' => 'value_2',
...
'attribute_n' => 'value_n',
]
在你的例子中,要将明天的日期转换为相应的数组,你可以使用:
//Get the timestamp for tomorrow
$tomorrow = time("tomorrow");
$date = [
//Converts the previous timestamp to an integer with the value of the
//year of tomorrow (to this date 2018)
'year' => (int)date('Y', $tomorrow),
//Same with the month
'month' => (int)date('m', $tomorrow),
//And now with the day
'day' => (int)date('d', $tomorrow),
];
$formData = array(
'date' => $date,
//some other fields
);
希望这有帮助