我已经阅读了很多关于 stackoverflow 的帖子。但是大多数方法在 Symfony 2.3 中没有用。所以我尝试在测试中手动登录用户以在后端进行一些操作。这是我的security.yml
security:
...
role_hierarchy:
ROLE_SILVER: [ROLE_BRONZE]
ROLE_GOLD: [ROLE_BRONZE, ROLE_SILVER]
ROLE_PLATINUM: [ROLE_BRONZE, ROLE_SILVER, ROLE_GOLD]
ROLE_ADMIN: [ROLE_BRONZE, ROLE_SILVER, ROLE_GOLD, ROLE_PLATINUM, ROLE_ALLOWED_TO_SWITCH]
providers:
database:
entity: { class: Fox\PersonBundle\Entity\Person, property: username }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/person/login$
security: false
main:
pattern: ^/
provider: database
form_login:
check_path: /person/login-check
login_path: /person/login
default_target_path: /person/view
always_use_default_target_path: true
logout:
path: /person/logout
target: /
anonymous: true
access_control:
- { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/person/registration, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/person, roles: ROLE_BRONZE }
这是我的测试:
class ProfileControllerTest extends WebTestCase
{
public function setUp()
{
$kernel = self::getKernelClass();
self::$kernel = new $kernel('dev', true);
self::$kernel->boot();
}
public function testView()
{
$client = static::createClient();
$person = self::$kernel->getContainer()->get('doctrine')->getRepository('FoxPersonBundle:Person')->findOneByUsername('master');
$token = new UsernamePasswordToken($person, $person->getPassword(), 'main', $person->getRoles());
self::$kernel->getContainer()->get('security.context')->setToken($token);
self::$kernel->getContainer()->get('event_dispatcher')->dispatch(
AuthenticationEvents::AUTHENTICATION_SUCCESS,
new AuthenticationEvent($token));
$crawler = $client->request('GET', '/person/view');
}
当我运行这个测试时,$person = $this->get(security.context)->getToken()->getUser();
方法在测试控制器中不起作用。说如果在控制器调用中$person->getId();
我会出错Call to a member function getId() on a non-object in...
。
那么你能说出在 Symfony 2.3 功能测试中登录用户的正确方法吗?
谢谢!
EDIT_1:如果我更改Symfony/Component/Security/Http/Firewall/ContextListener.php
并评论一个字符串:
if (null === $session || null === $token = $session->get('_security_'.$this->contextKey)) {
// $this->context->setToken(null);
return;
}
所有测试都在进行,没有错误。