我想对 Symfony2 服务进行一项功能测试。这个想法是在 Controller 之前调用,然后使用该函数加载服务。函数是这样的:
function save($title,$description,$setId,$html,$validate,$articles){
$articles = explode(',', $articles);
if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
throw new \Exception("Not allowed");
}else{
$profileId = $this->container->get('security.context')->getToken()->getUser()->getId();
$userName = $this->container->get('security.context')->getToken()->getUser()->getUserName();
}
}
现在我的测试代码是:
$client = static::createClient();
$crawler = $client->request('GET','/sets/save',
array(
"title"=>"rtyui",
"description"=>"aksdjhashdkjahskjdh",
"set_id"=>"",
"html"=>"",
"validate"=>1,
"articels"=>"3,4"
)
);
但我有以下几行已经不起作用:
if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
throw new \Exception("Not allowed");
现在的问题是,我如何进行验证过程?我尝试执行此验证过程,如文档所示:
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'username',
'PHP_AUTH_PW' => 'pa$$word',
));
但我遇到了同样的错误。
最佳答案
您还可以通过安全 token 登录用户:
$client = static::createClient();
$container = $client->getContainer();
$container->get('security.context')->setToken(
new UsernamePasswordToken(
$user, null, 'main', $user->getRoles()
)
);
地点:
$user
- 具有角色ROLE_USER
的用户实体实例,main
- 您的安全提供商名称
关于symfony - get ('security.context' )->在功能测试中被授予,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10898419/