Symfony和PhpUnit内存泄漏

Ced*_*ric 7 phpunit doctrine symfony

在我们的phpunit测试中加载Doctrine时,我们遇到内存泄漏问题

从Symfony的文档开始:http: //symfony.com/doc/2.7/cookbook/testing/doctrine.html我们编写了这个测试:

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class memoryleakTest extends KernelTestCase
{
    private $em;

    protected function setUp()
    {
        self::bootKernel();

        $this->em = static::$kernel->getContainer()
            ->get('doctrine')
            ->getManager();
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->em->close();
    }

    function testEEE1()  { 
    }
    function testEEE2()  { 
    }
    function testEEE3()  { 
    }
    function testEEE4()  { 
    }
    function testEEE5()  { 
    }
    function testEEE6()  { 
    }
    function testEEE7()  { 
    }
    function testEEE8()  { 
    }
    function testEEE9()  { 
    }
    function testEEE10()  { 
    }
    function testEEE11()  { 
    }
    function testEEE12()  { 
    }
    function testEEE13()  { 
    }
    function testEEE14()  { 
    }
    function testEEE15()  { 
    }
    function testEEE16()  { 
    }
}
Run Code Online (Sandbox Code Playgroud)

我们得到了这个结果(括号内的php_memory_usage):

testEEE1: . (42M)
testEEE2: . (42.7M)
testEEE3: . (43.3M)
testEEE4: . (44M)
testEEE5: . (44.8M)
testEEE6: . (45.5M)
testEEE7: . (46.1M)
testEEE8: . (46.8M)
testEEE9: . (47.4M)
testEEE10: . (48.1M)
testEEE11: . (48.7M)
testEEE12: . (49.4M)
testEEE13: . (50.1M)
testEEE14: . (50.7M)
testEEE15: . (51.4M)
testEEE16: . (52M)
Run Code Online (Sandbox Code Playgroud)

如果我们删除在设置中加载的学说管理器,我们得到(32,7M)每个测试

在拆解功能中的每次测试后卸载学说是否是正确的方法?

Ced*_*ric 6

完整的解决方案如下所示:https: //github.com/symfony/symfony/issues/18236

对于phpunit测试中使用的每个服务,如果希望垃圾收集器释放内存,则必须通过为变量赋值null来释放它.

protected function tearDown()
{
    parent::tearDown();

    $this->em->close();

    $this->em=null;

    gc_collect_cycles();
}
Run Code Online (Sandbox Code Playgroud)


Lui*_*pes 5

为了使您更轻松地进行操作,可以使用带有拆解功能的BaseTestCase.php并将其放入其中:

// Remove properties defined during the test
    $refl = new \ReflectionObject($this);
    foreach ($refl->getProperties() as $prop) {
        if (!$prop->isStatic() && 0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) {
            $prop->setAccessible(true);
            $prop->setValue($this, null);
        }
    }
Run Code Online (Sandbox Code Playgroud)

那段代码将使您免于头痛:)

  • 这很好用,将我的内存占用减少了一半。谢谢! (2认同)