Symfony2 testing with PHP unit quick tip

I ran into a few issues running tests for a symfony2 project that seems to be common to many people once your test suite starts to be more important. One of the common issues that people encounter is that the number of PDO connections allowed was maxed out. Doctrine keeps the connections alive in case a re-use is needed, but for now doesn’t close the connections once the Kernel shuts down (see: This issue has been closed as not related to Symfony, but I can’t figure out whether it’s been updated in the Doctrine bundle. So far it doesn’t seem so.

The workaround proposed in the 2 issues referencing that problem has allowed me to do a few more tests until the same problem appeared again. The solution that works best for me was to actually close the Doctrine connection on the tearDown of the PHPUnit test like this:

Now I run all my tests without ever having this issue come up again.


Even better, my tests run WAY faster than they did before! The normal test run is between 10 to 30% faster like this. But running the tests with code coverage now takes me less than half of the time it did before this change.

5 thoughts on “Symfony2 testing with PHP unit quick tip

  1. Pingback: - We are php

  2. Hi,

    Good to know I wasn’t the only one experiencing this. I too tried the fix mentioned in the ticket but it only lasted a few weeks before the issue popped up again.
    I haven’t had success using the tearDown() approach either. Are you including this function in every Test class?
    Because $this->getContainer() is not available. I tried
    but that doesn’t do the trick.
    I’m using the Symfony2 version1.0 so maybe some things have changed?
    Any help would be greatly appreciated.

    • Ah, this is because I inherit my tests from my own test case class in order to add some functionality required in most of my tests (like loading fixtures etc …).

      So indeed, to get the container, you almost got it, your tests usually will look like:
      $client = $this->createClient();
      // perform my test
      // end of test

      or in my case:
      $this->client = $this->createClient();
      // do things

      Then the teardown can be:
      public function tearDown(){

Comments are closed.