goto
goto

Reputation: 8162

Too many connection during unit testing

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

Upvotes: 4

Views: 3133

Answers (1)

munkie
munkie

Reputation: 76

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

Upvotes: 6

Related Questions