单元测试期间连接太多

got*_*oto 3 phpunit automated-tests symfony

我有一个像很多测试类的项目

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
         */
}
Run Code Online (Sandbox Code Playgroud)

它们都扩展了我的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");

}
Run Code Online (Sandbox Code Playgroud)

由于我有很多测试,我最近遇到了一些错误 PDOException: SQLSTATE[08004] [1040] Too many connections.这就像phpunit从不关闭数据库连接,大约100次测试我得到了所有其他测试的错误.

我该如何解决?

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

一些额外的信息:我很确定我没有一个测试的问题,因为如果我更改测试套件的顺序,错误出现在相同数量的测试类传递

小智 5

我的解决方案是覆盖我的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();
    }
}
Run Code Online (Sandbox Code Playgroud)