Reputation: 749
In upgrading Symfony 3.4 to Symfony 4.2 I have all unit test passing apart from functional tests on controllers where Twig is being rendered and using app.session.get('my_session_variable')
.
Using the standard app.session
, the session
is always null
.
I get the error:
Twig\Error\RuntimeError : Impossible to invoke a method ("get") on a null variable.
It appears the session is not getting set, even when I explicitly set a session in the test setup via:
$this->client->getContainer()->get('session')->set('my_session_variable', 'help');
The code is like the following:
Test class:
final class HomepageTest extends WebtestCase
{
public function setUp(): void
{
parent::setUp();
$this->client = static::createClient();
$this->router = $this->client->getContainer()->get('router');
}
public function testMyPatience(): void
{
$url = $this->router->generate('homepage');
$this->client->request('GET', $url);
$this->assertSame(200, $this->client->getResponse()->getStatusCode());
}
}
Controller class:
final class Homepage extends AbstractController
{
/**
* @Route("/homepage", name="homepage", methods={"GET"})
*/
public function index(): Response
{
return $this->render('homepage.html.twig');
}
}
Twig template:
{% if app.session.get('my_session_variable') != null %}
<p>Session variable is set</p>
{% endif %}
config/test/framework.yaml:
framework:
test: true
session:
storage_id: session.storage.mock_file
Upvotes: 0
Views: 857
Reputation: 749
For anyone else who has this issue, the solution was to use:
app.request.session.get('my_session_variable')
Instead of:
app.session.get('my_session_variable')
Upvotes: 1