为此,您需要创建一个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;