php - Testing Symfony2 session

980

Here is the action in my controller code:

//DefaultController.php
public function resultsAction(Request $request)
{
    $session = $request->getSession();
    $data = $session->get('custom_data');
    var_dump($data);
    //...
}

Here is my test code:

//DefaultControllerTest.php
public function setUp()
{
    $this->client = static::createClient(array(), array(
            'HTTP_USER_AGENT' => 'MySuperBrowser/1.0',
        ));
    $this->client->insulate();
    $this->client->followRedirects(true);
    $sessionMock = new MockFileSessionStorage();
    $this->session = new Session($sessionMock);
}

public function testAdslRisultati()
{
    $data = array(
        'key1' => 'val1',
        'key2' => 'val2' //etc...,
    );
    $this->session->set('custom_data', $data);
    $crawler = $this->client->request('GET', '/results');
    $this->assertTrue($crawler->filter('html:contains("text...")')->count() > 0);
}

When I execute the test, the value of $data in the controller is always empty. How can I save any data in session from test and retry it from controller?

//config_test.yml
framework:
test: ~
session:
    storage_id: session.storage.mock_file

Thank you very much

736

Answer

Solution:

Your can get the session storage from container in client

As example:

$this->client->getContainer()->get('session')->set('foo_bar', 'Bar');

Attention: The container in client used only for one request ($client->request()).

People are also looking for solutions to the problem: javascript - how to keep the session active even i opened in multiple tabs in same browser

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.