繁体   English   中英

具有构造函数的Symfony 3单元测试表格

[英]Symfony 3 unit test form with constructor

我试图对具有2个依赖项(ObjectManager和EventDispatcher)的表单进行单元测试

我曾尝试遵循官方文档,但没有成功。

我的测试文件:

<?php

namespace Lch\MediaBundle\Tests\Form;

use Lch\MediaBundle\Form\AddImageType;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;

class AddImageTypeTest extends TypeTestCase
{
    private $entityManager;
    private $eventDispatcher;

    protected function setUp()
    {
        $this->entityManager = $this->createMock(ObjectManager::class);
        $this->eventDispatcher = $this->createMock(EventDispatcher::class);

        parent::setUp();
    }

    protected function getExtensions()
    {
        $type = new AddImageType($this->entityManager, $this->eventDispatcher);

        return array(
            new PreloadedExtension(array($type), array()),
        );
    }

    public function testSubmitValidData()
    {
        $form = $this->factory->create(AddImageType::class);
    }
}

执行测试套件时出现此错误:

TypeError:传递给LCH \\ MediaBundle \\ Form \\ AddImageType :: __ construct()的参数1必须实现接口Doctrine \\ Common \\ Persistence \\ ObjectManager,没有给出接口,在/ home / matthieu / www / lch / media / src / Lch / MediaBundle中调用/vendor/symfony/symfony/src/Symfony/Component/Form/FormRegistry.php在第85行

看来我在getExtensions方法中所做的工作没有用,但无法解决。

有人有线索吗?

ObjectManager是一个接口,这意味着您无法实例化或将其直接传递给其他构造函数。

如果使用的是Doctrine,则将其替换为实现ObjectManager接口并可以实例化的Doctrine\\ORM\\EntityManager ,否则将其替换为自己的实现。

<?php

namespace Lch\MediaBundle\Tests\Form;

use Lch\MediaBundle\Form\AddImageType;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;

class AddImageTypeTest extends TypeTestCase
{
    private $entityManager;
    private $eventDispatcher;

    protected function setUp()
    {
        $this->entityManager = $this->createMock(EntityManager::class);
        $this->eventDispatcher = $this->createMock(EventDispatcher::class);

        parent::setUp();
    }

    protected function getExtensions()
    {
        $type = new AddImageType($this->entityManager, $this->eventDispatcher);

        return array(
            new PreloadedExtension(array($type), array()),
        );
    }

    public function testSubmitValidData()
    {
        $form = $this->factory->create(AddImageType::class);
    }
}

暂无
暂无

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

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