php - 设置 session 变量以在 Symfony Controller 中使用重定向 PHPUnit 测试

标签 php symfony session phpunit functional-testing

我正在尝试创建一个功能测试,该测试涉及跨重定向保留 session 变量。登录部分似乎有效,但我无法设置和保留 session 变量。

测试类扩展 WebTestCase。

$this->client = static::createClient();
$this->client->followRedirects();

身份验证

$user = $em->getRepository('MyApp\AppBundle\Entity\User')
        ->findOneByUsername('gagarin');
$firewall = 'secured_area';
$token = new UsernamePasswordToken($user, $user->getPassword(),
        $firewall, $user->getRoles());
self::$kernel->getContainer()->get('security.context')->setToken($token);
$session = $this->client->getContainer()->get('session');
$session->set('_security_' . $firewall, serialize($token));
// tried $session->set('color_id', 1234) here
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);

“/”路由将重定向到登录页面,然后返回到“/”页面 因为 followRedirects 设置为 true。

$crawler = $this->client->request(
        'GET',
        'http://myapp.test/');
$this->assertTrue($this->client->getResponse()->isSuccessful());

我想做的是设置一个 session 变量(color_id),我可以断言它存在于请求的路由上,然后重定向到登录或“/”路由到的其他页面基于颜色_id。我该怎么做?

最佳答案

我已将身份验证放在自己的类 AbstractControllerTest 中。 以下是 session 处理的相关代码:

abstract class AbstractControllerTest extends WebTestCase
{
    protected $session = [];

    public function addSession($session): void
    {
        $this->session = array_merge($this->session, $session);
    }

    protected function createAuthorizedClient()
    {
        //Here comes your client logic...

        foreach ($this->session as $sessionKey => $sessionValue) {
            $session->set($sessionKey, $sessionValue);
        }

        $container->get('session')->save();
        $client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));

        return $client;
    }
}

在您的测试中使用 AbstractControllerTest 并在您的 setUp() 方法中设置额外的 session 变量,如下所示:

class MyTest extends AbstractControllerTest
{
    public function setUp(): void
    {
        $this->addSession(['variable' => 'value']);

        parent::setUp();
    }
}

关于php - 设置 session 变量以在 Symfony Controller 中使用重定向 PHPUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38011003/

相关文章:

symfony - Symfony/twig 中的分组复选框

nhibernate - 是否可以为 NHibernate session 中的所有实体启用/禁用延迟加载?

php - 使用 PHP session 在表单之间保存数据是否正确?

php - 交响乐 2 : Install and enable the intl extension

PHP 错误报告和 mail()

PHP - 发送带附件的电子邮件不显示邮件内容

php - Sylius:如何在自定义 ProductRepository 中注入(inject)(请求)参数?

php - 事件记录 : Working with a db object

forms - Symfony2 表单实体更新

ruby-on-rails - 有没有一种简单的方法可以在 Rails 和 Node.js 应用程序之间共享存储在 Redis 中的 session 数据?