gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:18:42 24 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

然后我们在 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;
}

关于phpunit - 如何在 PHPUnit 测试中在 Symfony 中设置参数或服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41984143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com