Symfony2容器/内核的测试性能

时间:2014-02-14 13:29:25

标签: unit-testing symfony

我在大多数测试用例中使用LiipfunctionalBundle,即使它们是单位。只是因为那里的“便利”方法。最近我意识到我的测试性能非常糟糕,即使对于服务的单个单元测试也是如此。

这个问题主要是因为我从容器中获取服务。在LiipTestBundle中需要创建Kernal并启动它:

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];
}

在我的一些情况下,在“测试”环境中启动需要6-10秒。有时只有2s。但它仍然很慢,我想知道为什么这么慢,我能做些什么呢。我已经开始在自己的测试用例中创建服务而不是使用容器。但这也意味着更多的努力来创建测试用例。

1 个答案:

答案 0 :(得分:0)

嗯,“便利”正在杀死你。您只能将LiipfunctionalBundle与功能测试一起使用。按照目前的路径,您很快就会发现您的测试很难维护。

如果您想快速测试,请编写更多单元测试。正确使用依赖注入。不要将容器注入到类中(我只是猜测为什么选择在测试中使用内核或容器)。

dev test 环境中,监视资源,以便在配置文件更改时刷新缓存。这很可能是它比 prod 环境慢的原因。

相关问题