gpt4 book ai didi

php - 在 phpunittest 中访问实体管理器

转载 作者:可可西里 更新时间:2023-10-31 22:12:35 24 4
gpt4 key购买 nike

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

关于php - 在 phpunittest 中访问实体管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16773764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com