簡體   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