Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Symfony 4测试中Twig中的会话始终为空_Php_Symfony_Twig_Phpunit_Symfony4 - Fatal编程技术网

Php Symfony 4测试中Twig中的会话始终为空

Php Symfony 4测试中Twig中的会话始终为空,php,symfony,twig,phpunit,symfony4,Php,Symfony,Twig,Phpunit,Symfony4,在将Symfony 3.4升级到Symfony 4.2的过程中,除了对正在呈现细枝的控制器进行功能测试外,我还使用app.session.get('my\u session\u variable') 使用标准的应用程序会话,会话始终为空 我得到一个错误: Twig\Error\RuntimeError : Impossible to invoke a method ("get") on a null variable. 即使我通过以下方式在测试设置中显式设置会话,会话似乎也未设置: $this

在将Symfony 3.4升级到Symfony 4.2的过程中,除了对正在呈现细枝的控制器进行功能测试外,我还使用
app.session.get('my\u session\u variable')

使用标准的
应用程序会话
会话
始终为

我得到一个错误:

Twig\Error\RuntimeError : Impossible to invoke a method ("get") on a null variable.
即使我通过以下方式在测试设置中显式设置会话,会话似乎也未设置:

$this->client->getContainer()->get('session')->set('my_session_variable','help')

代码如下所示:

测试等级:

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());
    }
}
控制器类:

final class Homepage extends AbstractController
{
    /**
     * @Route("/homepage", name="homepage", methods={"GET"})
     */
    public function index(): Response
    {
        return $this->render('homepage.html.twig');
    }
}
细枝模板:

{% if app.session.get('my_session_variable') != null %}
    <p>Session variable is set</p>
{% endif %}

对于存在此问题的任何其他人,解决方案是使用:

app.request.session.get('my_session_variable')
而不是:

app.session.get('my_session_variable')

@TomPaler的可能副本不幸的是,我试图以标准方式(
app.Session
)访问Session对象,正如您提到的答案中所强调的那样,但问题是这不起作用。但是,使用
app.request.session
会起作用。
app.session.get('my_session_variable')