开发者

How to use an authenticated user in a Symfony2 functional test?

开发者 https://www.devze.com 2023-03-16 17:40 出处:网络
I use the FacebookBundle to authenticate users in my Symfony2 application. However, I would like to create functional tests with phpunit which uses an authenticated user.

I use the FacebookBundle to authenticate users in my Symfony2 application. However, I would like to create functional tests with phpunit which uses an authenticated user.

Moreover, I don't want to use a facebook开发者_运维知识库 user for this, but harcoded one.

Does anybody know how to implement this?


It's actually quite simple.

  1. Setup security.yml for test environment (it's a snippet from Symfony 2.0-RC3)

    security:
        encoders:
            Symfony\Component\Security\Core\User\User: plaintext
    
        providers:
            in_memory:
                users:
                    user:  { password: userpass, roles: [ 'ROLE_USER' ] }
                    admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] }
    
        firewalls:
             secured-area:
                 pattern:    ^/demo/secured/
                 http_basic:
                     realm: "Secured Demo Area"
    
  2. As you can see there is HTTP Authentication defined. So now, all you have to do is to setup a client in functional test:

    $client = static::createClient(array(), array(
        'PHP_AUTH_USER' => 'user',
        'PHP_AUTH_PW'   => 'userpass',
    ));
    

This link might be useful: http://symfony.com/doc/current/testing.html

0

精彩评论

暂无评论...
验证码 换一张
取 消