4

我在 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
4

1 回答 1

8

为此,您需要创建一个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;
于 2013-05-27T13:07:41.433 回答