访问phpunittest中的实体管理器


accessing entity manager inside phpunittest

我在symfony中有以下单元测试代码:

<?php
// src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php
namespace Shopious'MainBundle'Tests;
class ShippingCostTest extends 'PHPUnit_Framework_TestCase
{
    public function testShippingCost()
    {
        $em = $this->kernel->getContainer()->get('doctrine.orm.entity_manager');
        $query = $em->createQueryBuilder();
        $query->select('c')
              ->from("ShopiousUserBundle:City", 'c');
        $result =  $query->getQuery()->getResult();
        var_dump($result);
    }
}

和我试图访问这里的实体管理器,但它总是给我这个错误:

Undefined property: Acme'MainBundle'Tests'ShippingCostTest::$kernel

要实现这一点,您需要创建一个基本测试类(让我们称之为KernelAwareTest),其内容如下:

<?php
namespace Shopious'MainBundle'Tests;
require_once dirname(__DIR__).'/../../../app/AppKernel.php';
/**
 * Test case class helpful with Entity tests requiring the database interaction.
 * For regular entity tests it's better to extend standard 'PHPUnit_Framework_TestCase instead.
 */
abstract class KernelAwareTest extends 'PHPUnit_Framework_TestCase
{
    /**
     * @var 'Symfony'Component'HttpKernel'Kernel
     */
    protected $kernel;
    /**
     * @var 'Doctrine'ORM'EntityManager
     */
    protected $entityManager;
    /**
     * @var 'Symfony'Component'DependencyInjection'Container
     */
    protected $container;
    /**
     * @return null
     */
    public function setUp()
    {
        $this->kernel = new 'AppKernel('test', true);
        $this->kernel->boot();
        $this->container = $this->kernel->getContainer();
        $this->entityManager = $this->container->get('doctrine')->getManager();
        $this->generateSchema();
        parent::setUp();
    }
    /**
     * @return null
     */
    public function tearDown()
    {
        $this->kernel->shutdown();
        parent::tearDown();
    }
    /**
     * @return null
     */
    protected function generateSchema()
    {
        $metadatas = $this->getMetadatas();
        if (!empty($metadatas)) {
            $tool = new 'Doctrine'ORM'Tools'SchemaTool($this->entityManager);
            $tool->dropSchema($metadatas);
            $tool->createSchema($metadatas);
        }
    }
    /**
     * @return array
     */
    protected function getMetadatas()
    {
        return $this->entityManager->getMetadataFactory()->getAllMetadata();
    }
}

那么您自己的测试类将从这个扩展:

<?php
namespace Shopious'MainBundle'Tests;
use Shopious'MainBundle'Tests'KernelAwareTest;
class ShippingCostTest extends KernelAwareTest
{ 
    public function setUp()
    {
        parent::setUp();
        // Your own setUp() goes here
    }
    // Tests themselves
}
然后使用父类的类方法。在您的示例中,要访问实体管理器,请执行:
$entityManager = $this->entityManager;