【问题标题】:Mocking SecurityContext in Symfony2 using PHPUnit使用 PHPUnit 在 Symfony2 中模拟 SecurityContext
【发布时间】:2016-09-12 19:37:41
【问题描述】:

这些是我的模拟:

$this->user->method('getCustomerId')
           ->willReturn($this->customerId);
$this->userToken->method('getUser')
                ->willReturn($this->user);
$this->securityContext->method('getToken')
                      ->willReturn($this->userToken);
$this->securityContext->expects($this->once())
                      ->method('isGranted')
                      ->will($this->returnValue(true));

这是我正在测试的类的代码:

$token = $securityContext->getToken();
$isFullyAuthenticated = $securityContext->isGranted('IS_AUTHENTICATED_FULLY');

它抛出错误:

Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException: The security context contains no authentication token. One possible reason may be that there is no firewall configured for this URL.

我现在不知道该怎么做,尽管模拟拦截了对方法的调用并返回了我想要的任何内容。但在这种情况下,isGranted 方法似乎没有被模拟

【问题讨论】:

  • 不要嘲笑你不拥有的东西。只需创建一个实例并在其中放入一个令牌。

标签: php symfony phpunit


【解决方案1】:

尝试使用willReturn 代替will 并添加with

所以试试这个:

$this->securityContext->expects($this->once())
                      ->method('isGranted')
                      ->with('IS_AUTHENTICATED_FULLY')
                      ->willReturn(true);

而不是这个:

$this->securityContext->expects($this->once())
                      ->method('isGranted')
                      ->will($this->returnValue(true));

希望有帮助

【讨论】:

    【解决方案2】:

    我发现问题在于 isGranted 方法是最终的,因此无法模拟,解决问题的方法是模拟 SecurityContext 的所有属性,以便在调用该方法时返回我想要的输出,而不是使用模拟方法拦截调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 2012-12-19
      • 2020-09-28
      • 2020-10-25
      • 2015-11-01
      • 1970-01-01
      相关资源
      最近更新 更多