2017-11-11 70 views
1

当单元测试带有dateType字段的表单时,我的表单测试将始终为该字段返回null。单元测试Symfony表单DateType

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

这不仅仅是关于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 
); 

希望这有助于