访问phpunittest中的实体管理器
发布时间:2020-12-13 17:45:01 所属栏目:PHP教程 来源:网络整理
导读:我在symfony中有以下单元测试代码: ?php// src/Acme/DemoBundle/Tests/Utility/CalculatorTest.phpnamespace ShopiousMainBundleTests;class ShippingCostTest extends PHPUnit_Framework_TestCase{ public function testShippingCost() { $em = $this-k
我在symfony中有以下单元测试代码:
<?php // src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php namespace ShopiousMainBundleTests; 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: AcmeMainBundleTestsShippingCostTest::$kernel 解决方法
要实现这一点,您需要创建一个基本测试类(让我们称之为KernelAwareTest),其中包含以下内容:
<?php namespace ShopiousMainBundleTests; 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 SymfonyComponentHttpKernelKernel */ protected $kernel; /** * @var DoctrineORMEntityManager */ protected $entityManager; /** * @var SymfonyComponentDependencyInjectionContainer */ 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 DoctrineORMToolsSchemaTool($this->entityManager); $tool->dropSchema($metadatas); $tool->createSchema($metadatas); } } /** * @return array */ protected function getMetadatas() { return $this->entityManager->getMetadataFactory()->getAllMetadata(); } } 那么你自己的测试类将从这个扩展: <?php namespace ShopiousMainBundleTests; use ShopiousMainBundleTestsKernelAwareTest; class ShippingCostTest extends KernelAwareTest { public function setUp() { parent::setUp(); // Your own setUp() goes here } // Tests themselves } 然后使用父类的方法.在您的情况下,要访问实体管理器,请执行: $entityManager = $this->entityManager; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |