2014-01-17 106 views
3

我有一個項目有很多的測試類的像太多的連接

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:

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次測試,我得到了所有其他測試的這個錯誤。

我該如何解決?

我試圖把最後一次測試在每個測試類到底在幹什麼$this->em->close(),但它並沒有解決它

一些額外的信息:我敢肯定,我沒有問題與一個測試,因爲如果我改變測試套件的順序,似乎傳來傳

+0

EM不會關連接方法關閉。 http://stackoverflow.com/questions/7134469/doctrine-2-close-connection – Josef

+0

我有一個類似的問題http://stackoverflow.com/questions/24657671/unit-testing-too-many-open-files-and -too-many-connections-errors-after-upgr 也許你找到了解決辦法? – zIs

回答

4

我的解決方案相同量的測試類的錯誤是覆蓋關機方法在我的包類:

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