get('security.context') - > isGranted功能测试

Rub*_*ada 3 phpunit functional-testing symfony

我想在服务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();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我的测试代码是:

    $client = static::createClient();

    $crawler = $client->request('GET','/sets/save',
            array(
                    "title"=>"rtyui",
                    "description"=>"aksdjhashdkjahskjdh",
                    "set_id"=>"",
                    "html"=>"",
                    "validate"=>1,
                    "articels"=>"3,4"
                )
        ); 
Run Code Online (Sandbox Code Playgroud)

但是我已经没有这条线了:

if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
        throw new \Exception("Not allowed");
Run Code Online (Sandbox Code Playgroud)

现在,问题是,我如何进行验证过程?我试图做这个验证过程,如显示文档:

$client = static::createClient(array(), array(
    'PHP_AUTH_USER' => 'username',
    'PHP_AUTH_PW'   => 'pa$$word',
));
Run Code Online (Sandbox Code Playgroud)

但我得到了同样的错误.

小智 8

您也可以通过Security Token登录用户:

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

哪里:

  1. $user- 具有角色的用户实体的实例ROLE_USER,
  2. main - 您的安全提供程序名称