[英]Mocking SecurityContext in Symfony2 using PHPUnit
These are my mocks: 这些是我的模拟:
$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));
And this is the code of the class I am testing: 这是我正在测试的类的代码:
$token = $securityContext->getToken();
$isFullyAuthenticated = $securityContext->isGranted('IS_AUTHENTICATED_FULLY');
It throws the error: 它引发错误:
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.
I have no idea what to do at this point, I though mocks intercepted the call to methods and returned whatever I wanted. 我不知道此时该怎么办,尽管模拟程序拦截了对方法的调用并返回了我想要的任何东西。 But in this case is seems the isGranted methods is not being mock 但是在这种情况下,似乎isGranted方法没有被模拟
Try using willReturn
instead of will
and add the with
尝试使用willReturn
代替will
并添加with
So try this: 所以试试这个:
$this->securityContext->expects($this->once())
->method('isGranted')
->with('IS_AUTHENTICATED_FULLY')
->willReturn(true);
Instead of this: 代替这个:
$this->securityContext->expects($this->once())
->method('isGranted')
->will($this->returnValue(true));
Hope this help 希望这个帮助
我发现问题是isGranted
方法是最终方法,因此无法进行模拟,解决方法是模拟SecurityContext的所有属性,以便在调用该方法时返回我想要的输出,而不是拦截该调用用模拟方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.