【问题标题】:SF2 Functional tests : "Resetting the container is not allowed when a scope is active"SF2 功能测试:“当范围处于活动状态时,不允许重置容器”
【发布时间】:2016-10-02 00:05:52
【问题描述】:

我尝试在我的 SF2.8 应用上执行简单的功能测试:

  • PHPUnit 5.3.4
  • 命令行执行:phpunit -c app src/LCH/MultisiteBundle/Tests/Controller/SiteControllerTest

站点控制器测试:

class SiteControllerTest extends WebTestCase
{

    /**
     * {@inheritDoc}
     */
    protected function setUp()
    {
        $this->superadmin = static::createClient();
    }

    /*
     * @group multisite
     */
    public function testList()
    {
        // Nothing here yet.
    }

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

PHPUnit 返回:

有 1 个错误:

1) LCH\MultisiteBundle\Tests\Controller\SiteControllerTest::testList Symfony\Component\DependencyInjection\Exception\LogicException:当作用域处于活动状态时,不允许重置容器。

/var/www/html/sites/lch/loyalty/app/bootstrap.php.cache:2231 /var/www/html/sites/lch/loyalty/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php:182 /var/www/html/sites/lch/loyalty/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php:192 /var/www/html/sites/lch/loyalty/src/LCH/MultisiteBundle/Tests/Controller/SiteControllerTest.php:29

这是由 Container 类本身在 reset() 方法中抛出的:

    /**
     * {@inheritdoc}
     */
    public function reset()
    {
        if (!empty($this->scopedServices)) {
            throw new LogicException('Resetting the container is not allowed when a scope is active.');
        }

        $this->services = array();
    }

但我找不到原因。到目前为止,我的服务注册中没有使用范围,所以它应该是默认的 self::SCOPE_CONTAINER 一个....

有什么提示吗?

非常感谢!

【问题讨论】:

    标签: php symfony testing phpunit


    【解决方案1】:

    感谢找到解决方案的Matmouth

    一开始,由于我们在某些 CLI 调用中需要请求对象,因此我们仅在 CLI 的容器中实现了请求注入: AppKernel.php:

    protected function initializeContainer() {
            parent::initializeContainer();
    
            if (PHP_SAPI == 'cli') {
                $this->getContainer()->enterScope('request');
                $this->getContainer()->set('request', new \Symfony\Component\HttpFoundation\Request(), 'request');
            }
        }
    

    这不依赖于环境,即当测试用例加载“测试”环境时,注入空请求,创建上述异常。

    因此我们添加了测试环境排除,一切都很好:

    protected function initializeContainer() {
            parent::initializeContainer();
    
            if (PHP_SAPI == 'cli' &&  $this->getEnvironment() != 'test') {
                $this->getContainer()->enterScope('request');
                $this->getContainer()->set('request', new \Symfony\Component\HttpFoundation\Request(), 'request');
            }
        }
    

    【讨论】:

    • 你把你的initializeContainer方法放在哪里了?
    • 在 AppKernel 中,作为 Kernel::initializeContainer() 方法覆盖。
    猜你喜欢
    • 2014-06-01
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多