使用Symfony的flashBag会话进行单元测试

4

我正在使用Silex创建一个应用程序,并编写单元测试。

针对常规会话处理程序运行单元测试是没有问题的:

$app->register(new Silex\Provider\SessionServiceProvider(), array(
    'session.storage.options' => array(
        'cookie_lifetime' => 1209600, // 2 weeks
    ),
));

我在我的单元测试中设置了这个标志:

$this->app['session.test'] = true;

如果我不设置session.test标记,我的单元测试会抛出头部已发送错误并全部失败。而如果设置了这个标记,我的测试就可以正常运行。

问题在于我想使用flashBag功能(只保留到第一次请求后被删除的会话信息):

$foo = $app['session']->getFlashBag()->all();

flashBag似乎不尊重session.test标记,并且试图发送头文件,这会导致所有单元测试失败:

24) Yumilicious\UnitTests\Validator\PersonAccountTest::setConstraintsPassesWithMinimumAttributes RuntimeException: Failed to start the session because headers have already been sent.

/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

我已将问题缩小到此代码:https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php#L259 具体而言,是第262行。注释掉这一行就可以让我的测试正常工作并且全部通过。
我已经做了很多搜索来解决这个问题,但是没有任何进展。我认为这是因为flashBag是新功能(https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Session/Session.php#L305),旧方法正在被弃用。
如果你有任何建议来解决我的单元测试问题,那将非常棒。

今天我在 Silex 2.0-dev 上遇到了同样的问题。但是,堆栈上的任何答案都没有起作用。我在这里想出了一个可能的答案:https://dev59.com/-mvXa4cB1Zd3GeqPIV7A#34005216 - Heah
3个回答

4

为了进行测试,您需要使用MockArraySessionStorage实例替换session.storage服务:

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

$app['session.storage'] = new MockArraySessionStorage();

这是因为原生方法试图通过header发送cookie,这在测试环境中显然会失败。
编辑:现在有一个session.test参数,您应该将其设置为true。这将自动使会话使用模拟存储。

3

我也遇到过这种情况,如果我没有记错的话,通过使用不同的环境来运行我的单元测试就可以解决问题了,该环境具有

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

在config_test.yml中进行设置


0
我今天遇到了类似的问题,临时解决方法是在代码块中加上注释。
\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.');
   }
   */

这个解决方案可以保持测试的“绿色”,并且看起来应用程序会话功能也不会受到影响。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接