Symfony 6中的Phpunit测试表单

dvtswwa3  于 10个月前  发布在  PHP
关注(0)|答案(1)|浏览(79)

我正在尝试为包含Datime对象的表单编写测试。其他字段正在工作,但日期时间总是像预期的那样出现在结果中,因此测试失败。有人知道为什么会这样吗?
这是我的代码

public function testSubmitValidData(): void
{
    $date = new \DateTime('2023-06-05 00:00:00');
    $formData = [
        'name' => 'test name',
        'description' => 'test description',
        'price'=>100,
        'purchased_at' => $date
    ];

    $model = new Product();
    $form = $this->factory->create(ProductType::class, $model);

    $expected = new Product();

    $expected->setPurchasedAt($date);
    $expected->setName('test name');
    $expected->setDescription('test description');
    $expected->setPrice(10000);

 
    $form->submit($formData);

    // This works
    $this->assertTrue($form->isSynchronized());

    
    // this is not working because of Datetime object
    $this->assertEquals($expected, $model);
}

字符串
以下是测试结果:

1) App\Tests\Form\Type\TestedTypeTest::testSubmitValidData
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
     'name' => 'test name'
     'description' => 'test description'
     'price' => 10000
-    'purchased_at' => DateTime Object (...)
     'user' => null
     'users' => Doctrine\Common\Collections\ArrayCollection Object (...)
 )


以下是ProductType中的日期条目

->add('purchased_at', DateTimeType::class, array(
                'label' => false,
                'attr' => array(
                    'class' => 'min date',
                    'required' => false,
                    'id' => 'purchased_at')))

vsnjm48y

vsnjm48y1#

请检查您的日期时间类型中的选项,因为我看不到您的date_widget和其他格式选项https://symfony.com/doc/current/reference/forms/types/datetime.html#date-widget,您可能希望$formData不是DateTime对象,而是其他一些东西,例如带日期的字符串,该选项决定如何处理输入
请调试你在setPurchasedAt中得到的参数,因为它应该被称为property access component的原因是默认情况下表单使用的。
请检查是否使用了正确的酒店入口。

相关问题