【问题标题】:Symfony: Can I change container parameters on run time?Symfony:我可以在运行时更改容器参数吗?
【发布时间】:2018-03-23 08:39:24
【问题描述】:

我对 Symfony 完全陌生,我尝试运行一些验收测试。到目前为止一切都很好,但是当我运行测试时,我得到如下响应:

当我使用 PostMan 运行我的 API 控制器时,我没有得到任何相关信息。只有当我在命令行中运行测试时才会有这个输出。

根据输出消息:

The "UsersBundle\Controller\UsersController" service is private, getting it from the contains is deprecated since Symfony 3.2 and will fail in 4.0. You should either make the service public, or stop using the container directly and use dependency injection instead.

除此之外,我没有在我的测试方法中直接使用UsersController

public function test_cannot_send_multiple_possword_reset_requests() {
    $client = static::createClient( $this->defaults );

    $client->request(
        'POST',
        '/api/v1/user-account/request/reset',
        [
            'username' => 'merianos',
        ],
        [],
        [
            'Content-Type' => 'application/json',
        ]
    );

    $this->assertEquals( 400, $client->getResponse()->getStatusCode() );
    $this->assertContains(
        'An email containing your password reset token has been send.',
        $client->getResponse()->getContent()
    );
}

我想知道是否可以在运行时仅针对我的单元/验收测试覆盖以下设置:

# /src/UsersBundle/Resources/config/services.yml
services:
    _defaults:
        public: false

当然,如果有任何其他方法可以达到相同的结果。

请注意,我使用的是 Symfony 3.4。

【问题讨论】:

  • 关于科幻新闻,symfony.com/blog/new-in-symfony-4-1-simpler-service-testing。他们在 4.1 中解决了您的问题。但是对于 3.4,我想您必须在测试环境中将所有服务定义为公共
  • @MatMouth,是的,这就是消息的解释。但我的问题是,是否有办法让我的服务仅在测试环境中公开。如果可能的话,您有什么想法吗?
  • 在您的 app/config/config_test.yml 中,简单地定义它:services: _defaults: public: true

标签: php symfony


【解决方案1】:

您应该能够在config_test.yml 中覆盖它。您可以在此处阅读有关环境的更多信息:https://symfony.com/doc/current/configuration/environments.html

【讨论】:

  • 我做到了,但没有运气:(
  • 应该不需要,但你可以尝试用SYMFONY_ENV=test 运行phpunit 吗?像SYMFONY_ENV=test php vendor/phpunit/phpunit/phpunit这样不行,恐怕你得复制粘贴服务文件了。
【解决方案2】:

最后我以完全不同的方式破解它:)

这是我的解决方案:

<!-- ./phpunit.xml.dist -->
<phpunit other="settings-here">
    <php>
        <!-- some other settings here -->
        <env name="environment" value="test" />
    </php>
    <!-- Rest of the settings -->
</phpunit>

然后我这样做了:

<?php
// ./src/UsersBundle/Resources/config/environment-setup.php

if (
    isset( $_ENV['environment'] ) &&
    in_array( $_ENV['environment'], [ 'test', 'acceptance' ] )
) {
    $container->setParameter( 'public_services', true );
} else {
    $container->setParameter( 'public_services', false );
}

最后我做到了:

# ./src/UsersBundle/Resources/config/serviecs.yml

imports:
    - { resource: environment-setup.php }

services:
    _defaults:
        public: '%public_services%'
    # Rest of the setup.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 2019-06-06
    • 2017-08-13
    • 1970-01-01
    相关资源
    最近更新 更多