2017-11-11 21 views
1

ユニットがdateTypeフィールドを持つフォームをテストするとき、フォームテストは常にそのフィールドに対してnullを返します。ユニットテストSymfonyフォームの日付タイプ

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

それはちょうど約DateTypeではありません。submitメソッドは、オブジェクトを処理しないと、オブジェクトが用意されている場合nullに、このようなフィールドを設定します。このメソッドを使用する前に、を配列に変換する必要があります。あなたは、このスキーマに従わなければならない:

[ 
    'attribute_1' => 'value_1', 
    'attribute_2' => 'value_2', 
    ... 
    'attribute_n' => 'value_n', 
] 

あなたexempleでは、対応する配列に明日の日付を変換するために、あなたが使用することができます。

//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 
); 

が、これは

を役に立てば幸い
関連する問題