Symfony2 phpunit测试认证

时间:2016-01-22 13:22:42

标签: php symfony phpunit

谁可以帮助我在PHP功能测试中进行身份验证。我进行授权并且所有控制器测试都失败了,因为他们在localhost /之后没有得到任何东西,因为需要角色ROLE_USER。

我不知道如何在控制器测试中使用它。如果此电子邮件存在于具有用户实体和重定向的db create session中,则我的步骤中的授权看起来像输入表单电子邮件并提交输入。

但是如何在测试中效仿呢?

例如我测试的一部分。

public function testUnlinkWatcher()
{
    $client = static::createClient();
    $client->request('POST', 'project/client/unlink_watcher');


    $this->assertTrue($client->getResponse()->isSuccessful()); // this false because access denied

}

我尝试用2个例子,但是我不能工作。什么可以做?

private $client = null;

public function setUp()
{
    $this->client = static::createClient();
}

private function logIn()
{
    $session = $this->client->getContainer()->get('session');

    $firewall = 'secured_area';
    $token = new UsernamePasswordToken('login', null, $firewall, array('ROLE_USER'));
    $session->set('_security_'.$firewall, serialize($token));
    $session->save(); // It's here object session with roles
}

public function testUnlinkWatcher()
    {

        $this->logIn();                           
        $this->client->request('POST', 'testProject/client/unlink_watcher');

        var_dump($client->getResponse()->isSuccessful());die; //false

我的安全

security:

providers:
    in_memory:
        memory: ~

    hwi:
        entity: { class: Test\testProjectBundle\Entity\User }

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt|error)|css|images|js)/
        security: false

    secured_area:

        anonymous: ~

        oauth:
            resource_owners:
                google:             "/login/check-google"
                facebook:           "/login/check-facebook"
            login_path:        /
            failure_path:      /


            oauth_user_provider:
                service: testProjectbundle.oauth_provider

        logout: 
            path: /logout


access_control:
    - { path: ^/testProject(.+), roles: ROLE_USER }
logIn方法中的

会话转储:

    Symfony\Component\HttpFoundation\Session\Session {#377
  #storage: Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage {#376
    -savePath: "/var/www/integra/app/cache/test/sessions"
    #id: "e3723c3056f23247565a4abdafd2c3cc964cc6d425e6d51dfd70bc588b4ad78b"
    #name: "MOCKSESSID"
    #started: false
    #closed: false
    #data: array:3 [
      "_sf2_attributes" => &1 array:1 [
        "_security_secured_area" => "C:74:"Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken":227:{a:3:{i:0;N;i:1;s:12:"secured_area";i:2;s:178:"a:4:{i:0;s:5:"login";i:1;b:1;i:2;a:1:{i:0;O:41:"Symfony\Component\Security\Core\Role\Role":1:{s:47:"\x00Symfony\Component\Security\Core\Role\Role\x00role";s:9:"ROLE_USER";}}i:3;a:0:{}}";}}"
      ]
      "_sf2_flashes" => &2 []
      "_sf2_meta" => &3 array:3 [
        "u" => 1453705239
        "c" => 1453705239
        "l" => "0"
      ]
    ]

1 个答案:

答案 0 :(得分:1)