繁体   English   中英

单元测试Symfony表单DateType

[英]Unit Test Symfony Form DateType

当对带有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不包含任何其他方法。 所有其他字段都可以正常工作。

这不只是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
);

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM