当phpunit与symfony 2.X一起运行时,PDO连接未关闭

Gir*_*oft 8 connection phpunit symfony doctrine-orm

我们有大约180个单元测试实现webtestcase类,测试运行在控制器上.

但是,当我们运行单元测试时,它们会与db打开太多连接.由于过多的活动tcp连接测试在第120次测试后失败.测试运行时,所有连接都处于活动状态.

在tearDown函数中我们调用实体管理器的close函数,但没有任何东西,它没有任何影响.我认为有一些类保持连接对象引用.

因为在php手册中提到了关于pdo连接关闭时对象分配为null.我们也这样做,但没有变化.PS:我们的单元测试是功能测试.在控制器上工作并与db集成,没有模拟对象

我们的错误在哪里?我们如何解决这个问题?

这是我在config_test.yml中的连接参数

imports:
    - { resource: config_dev.yml }

framework:
    test: ~
    session:
        storage_id: session.storage.mock_file

web_profiler:
    toolbar: false
    intercept_redirects: false

doctrine:
    dbal:
        driver: pdo_mysql
        port: 3306
        host: localhost
        dbname: mydb
        user: myuser
        password: mypass
        charset: UTF8
Run Code Online (Sandbox Code Playgroud)

小智 7

你检查过phpunit.xml.dist文件了吗?

我想你应该看看这个; http://www.slideshare.net/fabpot/unit-and-functional-testing-with-symfony2

请确保您的参数在下面相同

<phpunit
    backupGlobals               = "false"
    backupStaticAttributes      = "false"
    colors                      = "true"
    convertErrorsToExceptions   = "true"
    convertNoticesToExceptions  = "true"
    convertWarningsToExceptions = "true"
    processIsolation            = "true"
    stopOnFailure               = "false"
    syntaxCheck                 = "false" 
    bootstrap                   = "bootstrap.php.cache" >
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是,这带来了另一个问题:"未捕获的PDOException:您无法序列化或反序列化PDO实例". (2认同)

con*_*nny 5

启用进程隔离会产生副作用,使测试套件的执行速度慢得多。

更好的方法是明确告诉 Doctrine 关闭其连接,无论是在测试tearDown、tearDownAfterClass还是任何这样注释的方法上,例如:

trait CloseConnectionAfterTestTrait {
    /** @after */
    public function avoidExhaustingDbConnections()
    {
        if(!empty($this->em)){
            $this->em->getConnection()->close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,消费者可以将他拥有的任何实体管理器实例保存为$this->em. 但是如果/自从您使用 Doctrine 后,您可能可以通过访问 Doctrine 服务来更好地概括代码static::$kernel->something