【问题标题】:Too many connection during unit testing单元测试期间连接过多
【发布时间】:2014-06-11 04:57:24
【问题描述】:

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

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 many connections。就像 phpunit 从不关闭数据库连接,大约 100 次测试我在所有其他测试中都得到了这个错误。

我该如何解决?

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

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

【问题讨论】:

标签: symfony phpunit automated-tests


【解决方案1】:

我的解决方案是在我的 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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多