简体   繁体   English

Symfony2容器/内核的测试性能

[英]Test Performance of Symfony2 Container / Kernel

I am using LiipfunctionalBundle for most of my testcases, even if they are unit. 我的大多数用例都使用LiipfunctionalBundle,即使它们是单元。 Just because of the "convenience" methods in there. 只是因为那里有“便利”方法。 Recently I realized that my test performance is really bad, even for single unit tests of services. 最近,我意识到我的测试性能确实很差,即使对于服务的单个单元测试也是如此。

This issue araises mainly if I get my services from the container. 如果我从容器中获得服务,则主要会出现此问题。 Which in the LiipTestBundle requires the creation of the Kernal and booting it: 在LiipTestBundle中,哪个需要创建内核并启动它:

protected function getContainer()
{
    if (!empty($this->kernelDir)) {
        $tmpKernelDir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : null;
        $_SERVER['KERNEL_DIR'] = getcwd().$this->kernelDir;
    }

    $cacheKey = $this->kernelDir.'|'.$this->environment;
    if (empty($this->containers[$cacheKey])) {
        $options = array(
            'environment' => $this->environment
        );
        $kernel = $this->createKernel($options);
        $start = microtime(true);
        $kernel->boot();
        $time = microtime(true) - $start;
        print('boot:'.$time.PHP_EOL);

        $this->containers[$cacheKey] = $kernel->getContainer();
    }

    if (isset($tmpKernelDir)) {
        $_SERVER['KERNEL_DIR'] = $tmpKernelDir;
    }

    return $this->containers[$cacheKey];
}

In some of my cases this booting in "test" environment takes 6-10s. 在我的某些情况下,在“测试”环境中启动需要6到10秒钟。 Sometimes only 2s. 有时只有2s。 But it is still very slow and I would like to know why this is so slow and what I could do about it. 但是它仍然很慢,我想知道为什么这么慢以及我能对此做些什么。 I already started creating services in my testcases on my own instead of using the container. 我已经开始自己在测试用例中创建服务,而不是使用容器。 But that also means more effort for creating test cases. 但这也意味着创建测试用例需要更多的精力。

Well, "convenience" is killing you. 好吧,“便利”正在杀死您。 You should only use the LiipfunctionalBundle with functional tests . 您只应将LiipfunctionalBundle与功能测试一起使用 Following your current path, you'll soon also find your tests hard to maintain. 按照当前的方式,您很快还会发现难以维护的测试。

If you want quick tests, write more unit tests. 如果要进行快速测试,请编写更多的单元测试。 Use dependency injection properly. 正确使用依赖项注入。 Don't inject the container into your classes (i'm only guessing WHY you chose to use the kernel or container in your tests). 不要将容器注入您的类中(我只是猜测您为什么选择在测试中使用内核或容器)。

In dev and test environments resources are monitored, so that if a config file changes, the cache is refreshed. 开发测试环境中,资源受到监视,因此,如果配置文件发生更改,则刷新缓存。 That's most likely the reason why it's slower than prod environment. 这很可能是它比生产环境慢的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM