如何在 PHPUnit 测试中设置 Symfony 中的参数或服务?

Mat*_*oli 7 phpunit symfony

我们正在使用 PHPUnit 来测试我们应用程序的部分内容。在某些测试中,我们想要更改参数的值或覆盖服务(但仅限于该测试,而不是所有测试)。

在测试中动态配置 Symfony 容器的推荐方法是什么?

我们遇到的问题是,当动态设置配置时,容器不会重新编译自身(因为它仅在文件更改时重新编译自身)。

Mat*_*oli 4

这就是我们现在的处理方式:

class TestKernel extends \AppKernel
{
    public function __construct(\Closure $containerConfigurator, $environment = 'test', $debug = false)
    {
        $this->containerConfigurator = $containerConfigurator;

        parent::__construct($environment, $debug);
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        parent::registerContainerConfiguration($loader);
        $loader->load($this->containerConfigurator);
    }

    /**
     * Override the parent method to force recompiling the container.
     * For performance reasons the container is also not dumped to disk.
     */
    protected function initializeContainer()
    {
        $this->container = $this->buildContainer();
        $this->container->compile();
        $this->container->set('kernel', $this);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我们在 PHPUnit 基测试类中添加了这个方法:

/**
 * Rebuilds the container with custom container configuration.
 *
 * @param \Closure $containerConfigurator Closure that takes the ContainerBuilder and configures it.
 *
 * Example:
 *
 *     $this->rebuildContainer(function (ContainerBuilder $container) {
 *         $container->setParameter('foo', 'bar');
 *     });
 */
public function rebuildContainer(\Closure $containerConfigurator) : ContainerInterface
{
    if ($this->kernel) {
        $this->kernel->shutdown();
        $this->kernel = null;
        $this->container = null;
    }

    $this->kernel = new TestKernel($containerConfigurator);
    $this->kernel->boot();
    $this->container = $this->kernel->getContainer();

    return $this->container;
}
Run Code Online (Sandbox Code Playgroud)