使用 PHPUnit 在 Symfony2 中模拟 SecurityContext

Mocking SecurityContext in Symfony2 using PHPUnit

这些是我的模拟:

$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));

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

$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 方法没有被模拟

尝试使用 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));

希望对您有所帮助

我发现问题是 isGranted 方法是最终的,所以不可能模拟,解决问题的方法是模拟 SecurityContext 的所有属性,以便在调用该方法时 returns 我想要的输出,而不是用模拟方法拦截调用。