单元测试期间连接过多 [英] Too many connection during unit testing

查看:20
本文介绍了单元测试期间连接过多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

它们都扩展了我的 BaseTestCase:

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");

}

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

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.

我该如何解决?

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

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

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

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

推荐答案

我的解决方案是在我的 Bundle 类中重写 shutdown 方法:

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

这篇关于单元测试期间连接过多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆