【问题标题】:Testing Symfony2 session测试 Symfony2 会话
【发布时间】:2014-07-08 10:20:16
【问题描述】:

这是我的控制器代码中的操作:

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

这是我的测试代码:

//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);
}

当我执行测试时,控制器中 $data 的值始终为空。如何从测试中保存会话中的任何数据并从控制器重试?

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

非常感谢

【问题讨论】:

    标签: php session symfony testing functional-testing


    【解决方案1】:

    您可以从客户端的容器中获取会话存储

    例如:

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

    注意:客户端中的容器仅用于一个请求($client->request())。

    【讨论】:

    • 感谢您的回答。现在我收到这个错误:RuntimeException: Failed to start the session 因为 headers 已经由第 172 行的“/var/www/project/vendor/phpunit/phpunit/PHPUnit/Util/Printer.php”发送。
    • 某处使用了真正的机制会话。请查看完整代码,您必须禁用真正的会话。
    猜你喜欢
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    相关资源
    最近更新 更多