如何在Symfony 2中进行需要身份验证的功能测试


How to make functional tests that require to be authenticated, in Symfony 2?

我找不到任何关于这个的文档。

我正在使用客户机对象向/login发送请求、填写表单并提交它。这工作得很好,但我得到一个302响应返回到/login,好像凭据不正确。

在任何情况下,我认为在第一个请求之后,会话表中至少应该有一行,但是没有。这怎么可能呢?

任何想法吗?

编辑:下面是代码:

    // Go to login page
    $client = $this->createClient();
    $crawler = $client->request('GET', '/login');
    $this->assertTrue($crawler->filter('html:contains("Username")')->count() > 0);
    // Fill in the form and submit it
    $form = $crawler->selectButton('login')->form();
    $form['_username'] = 'admin';
    $form['_password'] = 'admin';
    $client->submit($form);
    $this->assertEquals(302,$client->getResponse()->getStatusCode());
    $this->assertFalse($client->getResponse()->isRedirect('http://localhost/login'));

最后一个assert失败

您应该使用http基本身份验证创建一个新的防火墙:

<>之前安全:…防火墙:functional_test:模式:/安全/. *无状态:真http_basic:提供者:provider_name…之前

然后像这样创建一个客户端:

$client = $this->createClient(array(), array(
    'PHP_AUTH_USER' => 'username',
    'PHP_AUTH_PW' => 'password',
));

快乐编码!

到目前为止,官方文档包括文章如何在功能测试中使用令牌模拟身份验证。