gpt4 book ai didi

symfony - 单元测试期间连接过多

转载 作者:行者123 更新时间:2023-12-02 20:58:32 25 4
gpt4 key购买 nike

我有一个包含很多测试类的项目,例如

class MyTest extends BaseTestCase
{
public function __construct()
{
parent::__construct();
$this->em = $this->get('doctrine')->getManager();
}
public function setUp() {

$this->init();

//load sql data for the tests
$path = $this->get('kernel')->locateResource('@Bundle/Data/Test.sql');
$content_file_sql_data = file_get_contents($path);
$stmt = $this->em->getConnection()->prepare($content_file_sql_data);
$stmt->execute();
$stmt->closeCursor();
}
/*
* Then we do a lot of tests using the database
*/
}

它们都扩展了我的 BaseTestCase:

abstract class BaseTestCase extends \PHPUnit_Framework_TestCase {

protected $_container;
protected $kernel;

public function __construct() {

parent::__construct();
$this->kernel = new \AppKernel("test", true);
$this->kernel->boot();
$this->_container = $this->kernel->getContainer();

$this->init();
}

//empty the database before each test class
public function init() {

$this->_application = new Application($this->kernel);
$this->_application->setAutoExit(false);
//rebuild and empty the database
$this->runConsole("doctrine:schema:drop", array("--force" => true));
$this->runConsole("doctrine:schema:create");

}

由于我进行了大量测试,因此我最近遇到了一些错误PDOException: SQLSTATE[08004] [1040] Too much Connections。就像 phpunit 永远不会关闭数据库连接一样,大约 100 次测试后,我在所有其他测试中都会遇到此错误。

如何修复它?

我尝试在每个测试类的末尾进行最后一个测试 $this->em->close() 但没有解决问题

一些附加信息:我很确定我对一个测试没有问题,因为如果我更改测试套件的顺序,错误会出现在通过的相同数量的测试类周围

最佳答案

我的解决方案是重写 Bundle 类中的 shutdown 方法:

public function shutdown()
{
if ('test' == $this->container->getParameter('kernel.environment')) {
/* @var EntityManager $em */
$em = $this->container->get('doctrine.orm.default_entity_manager');
$em->getConnection()->close();
}
}

关于symfony - 单元测试期间连接过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21182087/

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