How to set some data in session in functional test?

1.6k Views Asked by At

I use "liip/functional-test-bundle": "~1.8", and "symfony/symfony": "~3.4", and for my functional test I want set some data in session,but after set data in action, with the same key, I had null. Mytest class extends from extends WebTestCase

this is how I set data in test method

    $session = $this->container->get('session');
    $session->set('test', 2);

    $this->getClient()->request(
        Request::METHOD_GET,
        $routing
    );

config_test.yml

framework:
test: ~
session:
    storage_id: session.storage.mock_file
    name: "MOCKSESSID"
profiler:
    collect: false

and in action

public function getEntityAction()
{
    $test = $this->get('session')->get('test');

variable $test equal null How to set some data in session in functional test ?

when debugging, before request

session = {Symfony\Component\HttpFoundation\Session\Session} [5]
 storage = {Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage} [8]
  savePath = "/tmp"
  id = "d5d7233a843594e94c42b6a0e5a14a86c2518fb5f0a6478732841547b3e93fd6"
  name = "MOCKSESSID"
  started = true
  closed = false
  data = {array} [3]
   _sf2_attributes = {array} [1]
    test = 2

and in action

$y = {Symfony\Component\HttpFoundation\Session\Session} [5]
    storage ={Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage} [8]
    savePath = "/home/ivan/hosts/fix/var/cache/test/sessions"
    id = "5ade2581b9764"
    name = "MOCKSESSID"
    started = true
    closed = false
    data = {array} [3]
        _sf2_attributes = {array} [1]
           _security_main = "authuser data"

I don't understand why id and savePath different ?

1

There are 1 best solutions below

0
On

As written here:

I think the main mistake here is forgetting that $this->container is NOT the same as $client->getContainer(): the Client spuns a completely separated, new container, and depending on how you use the session, you may not find the same stuff in both of them.

So when you call $this->container->get('session')->set('test', 2) you don't change the actual session of the test.


So, it may work if you call the container's client:

$client = $this->makeClient();
$client->getContainer()->set('test', 2);
$crawler = $client->request('GET', '/contact');

Or, in order to circumvent this issue, you can write a test that don't rely on setting the session directly but instead perform the same actions than the users do in order to populate the session and call the controller that use it.