3

我想对服务 Symfony2 进行一项功能测试。这个想法是先调用控制器,然后再用函数加载服务。功能是这个:

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',
));

但我得到了同样的错误。

4

1 回答 1

8

您也可以通过安全令牌登录用户:

$client = static::createClient();
$container = $client->getContainer();
$container->get('security.context')->setToken(
    new UsernamePasswordToken(
        $user, null, 'main', $user->getRoles()
    )
);

在哪里:

  1. $user- 具有角色的用户实体实例ROLE_USER
  2. main- 您的安全提供商名称
于 2012-09-07T07:46:17.257 回答