使用Symfony和x27进行单元测试;s的flashBag会话

使用Symfony和x27进行单元测试;s的flashBag会话,symfony,phpunit,silex,Symfony,Phpunit,Silex,我正在用Silex和单元测试创建一个应用程序 对常规会话处理程序运行单元测试效果良好: $app->register(new Silex\Provider\SessionServiceProvider(), array( 'session.storage.options' => array( 'cookie_lifetime' => 1209600, // 2 weeks ), )); 并在我的单元测试中设置此标志: $this->app

我正在用Silex和单元测试创建一个应用程序

对常规会话处理程序运行单元测试效果良好:

$app->register(new Silex\Provider\SessionServiceProvider(), array(
    'session.storage.options' => array(
        'cookie_lifetime' => 1209600, // 2 weeks
    ),
));
并在我的单元测试中设置此标志:

$this->app['session.test'] = true;
如果我没有设置session.test标志,我的单元测试将抛出headers ready sent错误,并且全部失败。有了它,我的测试运行得很好

问题是我正在尝试使用flashBag功能(会话信息仅持续到第一个请求,然后被删除):

flashBag似乎不尊重session.test标志,并尝试发送标头,这会导致我的所有单元测试失败:

(24) Yumilious\UnitTests\Validator\PersonAccountTest::SetConstraintsPasseWithMinimumAttribute RuntimeException:无法启动会话,因为标头已存在 已经发送了

/webroot/yumilicious/vendor/symfony/http-foundation/symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php:142 /webroot/yumilicious/vendor/symfony/http-foundation/symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php:262 /webroot/yumilicious/vendor/symfony/http-foundation/symfony/Component/HttpFoundation/Session/Session.php:240 /webroot/yumilicious/vendor/symfony/http-foundation/symfony/Component/HttpFoundation/Session/Session.php:250 /webroot/yumilicious/src/app.php:38 /webroot/yumilicious/tests/yumilicious/UnitTests/Base.php:13 /webroot/yumilicious/vendor/silex/silex/src/silex/WebTestCase.php:34 /webroot/yumilicious/vendor/EHER/PHPUnit/src/PHPUnit/PHPUnit.php:46 /webroot/yumilicious/vendor/EHER/PHPUnit/bin/PHPUnit:5

我已将其缩小为以下代码:

具体来说,第262行。注释出这一行允许我的测试正常工作,并且全部通过绿色

我花了不少时间才让它发挥作用,但我一点运气都没有。我想这是因为flashBag的东西是新的(https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Session/Session.php#L305)旧方法正在被弃用


任何关于让我的单元测试正常工作的建议都会非常棒。

对于测试,您需要将
会话.storage
服务替换为
MockArraySessionStorage
的实例:

use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;

$app['session.storage'] = new MockArraySessionStorage();
这是因为本地cookie试图通过
头发送cookie,这在测试环境中当然会失败


编辑:现在有一个
会话。test
参数应该设置为true。这将自动使会话使用模拟存储。

我今天遇到了类似的问题,临时修复方法是在中注释掉代码块

\Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage
start()
方法中

   /*
   if (ini_get('session.use_cookies')  && headers_sent()) {
       throw new \RuntimeException('Failed to start the session because headers have already been sent.');
   }
   */

此解决方案使测试保持“绿色”,从外观上看,应用程序会话功能保持原样。

我也遇到过这种情况,如果我没有弄错的话,我通过让我的单元测试在不同的环境中运行来解决了这一问题

framework:
    test: ~
    session:
        storage_id: session.storage.mock_file

在config_test.yml中设置。我今天在Silex 2.0-dev上遇到了相同的问题。
但是堆栈上的答案都没有解决这个问题。

我在这里找到了一个可能的答案:
framework:
    test: ~
    session:
        storage_id: session.storage.mock_file