【问题标题】:Unit Test Symfony Form DateType单元测试 Symfony 表单 DateType
【发布时间】:2017-11-11 10:11:20
【问题描述】:

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

【问题讨论】:

    标签: php symfony unit-testing


    【解决方案1】:

    这不仅仅是DateTypesubmit 方法不处理对象,如果提供了对象,会将这些字段设置为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
    );
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 2015-03-17
      • 2016-05-04
      相关资源
      最近更新 更多