繁体   English   中英

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

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

$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的所有属性,以便在调用该方法时返回我想要的输出,而不是拦截该调用用模拟方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM