Symfony2 功能测试会话持久化 [英] Symfony2 functional test session persistence

查看:64
本文介绍了Symfony2 功能测试会话持久化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Symfony 中进行功能测试,但目前我的会话遇到了问题.我执行了一段代码,它似乎正在运行,但我的容器会话中没有存储任何内容.

I'm trying to play a little bit with the functional test in Symfony and i'm currently facing a problem with my sessions. I execute a piece of code, which seems to be working, but nothing is stored inside the session of my container.

我有一个表格,您可以在其中设置数据.当您提交它时,它会检查值并将其存储在会话中.然后它重定向到另一个页面,其中需要存储在会话中的这些值.

I have a form where you set datas. When you submit it, it checks the values and store it inside sessions. Then it redirects to another page where these values stored in session are needed.

我测试的目的是检查会话.

The purpose of my test is to check the session.

<?php

namespace Acme\TestBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
use Symfony\Component\HttpFoundation\Session\Session;

class FrontControllerTest extends WebTestCase
{
    public function testForm()
    {
        $client = static::createClient();
        $session = $client->getContainer()->get('session');

        $crawler = $client->request('GET', '/setParameters');

        $form = $crawler->selectButton('Submit')->form();
        $form['myForm[firstname]']->setValue('Ben');
        $form['myForm[lastname]']->setValue('H');

        $client->submit($form);

        //I tested and my controller is fully going through the submit handler
        //which check the values and save it into the session
        //Things are 100% sure there. Then it redirects to another page which check those values.

        $values = $client->getContainer()->get('session')->get('parameters'); //NULL
        $this->assertEquals($values['firstname'], 'Ben'); //false
        $this->assertEquals($values['lastname'], 'H'); //false
    }
}

实际上它根本不起作用,似乎我无法在会话中存储任何内容并检索它.

Actually it's not working at all, it seems like i can't store anything in the session and retrieve it.

有人可以帮我吗?谢谢.

Can someone help me with it ? Thank's.

推荐答案

您在测试中使用的容器不是您触发的请求所使用的容器.Symfony 为每个请求创建新的容器.所以你不能直接通过容器访问会话.

The container you use in your test is not the container that is used by the requests you trigger. Symfony creates new containers for each request. So you can not access the session directly via the container.

另见http://alexandre-salome.fr/blog/Symfony2-隔离测试

一种可能的解决方案是从您的 cookie 中提取会话 ID,然后从您的会话存储中读取会话.

A possible solution would be to extract the session ID from your cookies and then read the session from your session storage.

这篇关于Symfony2 功能测试会话持久化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆