Too many connection during unit testing

空扰寡人 提交于 2019-12-22 10:59:44

问题


I have a project with a lot of tests class like

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
         */
}

They all extends my 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");

}

Since I have a lot of tests, i have recently got some errors PDOException: SQLSTATE[08004] [1040] Too many connections. It's like phpunit never close database connection, and around 100 tests I get this error for all the other tests.

How can i fix it?

I tried to put a last test doing $this->em->close() at the end of each test class but it didn't solve it

Some additional information: i'm pretty sure I don't have an issue with ONE test, because if I change the order of the test suite, the error appears around the same amount of tests class passed


回答1:


My solution was to override shutdown method in my Bundle class:

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();
    }
}


来源:https://stackoverflow.com/questions/21182087/too-many-connection-during-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!