2014-10-07 21 views
1

時,嘲笑security.context被視爲非對象。我試圖測試我的服務。此服務調用security.context等其他服務。當撥打AlbumHandler時,模擬在security.context步驟失敗。當調用

錯誤:

PHP Fatal error: Call to a member function getToken() on a non-object 

代碼:

 public function setUp() 
    { 
     $this->container = $this->getMock('\Symfony\Component\DependencyInjection\ContainerInterface'); 
    } 


     public function testAdd()                 
     { 

     // The user I want to return                       
     $user = $this->getMock('\MyProject\Bundle\UserBundle\Entity\User'); 

     // I create a Token for mock getUser()      
     $token = $this->getMock('\Symfony\Component\Security\Core\Authentication\Token');  
     $token->expects($this->once())               
       ->method('getUser')                
       ->will($this->returnValue($user));             

     // I mock the service. PHPUnit don't return an error here. 
     $service = $this->getMockBuilder('Symfony\Component\Security\Core\SecurityContextInterface') 
       ->disableOriginalConstructor()              
       ->getMock(); 
     $service->expects($this->once())               
       ->method('getToken')                
       ->will($this->returnValue($token));            

     // I replace the real service by the mock 
     $this->container->set('security.context', $service);         

     // It fails at the constructor of this service. 
     $albumHandler = new AlbumHandler($entityManager, $this->container, 'MyProject\Bundle\AlbumBundle\Entity\Album'); 

     $this->assertEquals($albumHandler, $albumHandler);          

     } 

下面的代碼是AlbumHandler

的constuctor
public function  __construct(ObjectManager $om, Container $container, $entityClass) 
    {                       
    $this->om = $om;                   
    $this->entityClass = $entityClass;              
    $this->repository = $this->om->getRepository($this->entityClass);      
    $this->container = $container; 

    // fail here              
    $this->user = $this->container->get('security.context')->getToken()->getUser();   
    } 

回答

5

必須嘲笑容器得到調用了。嘗試替換此:

// I replace the real service by the mock 
    $this->container->set('security.context', $service);         

$this->container 
     ->expects($this->once()) 
     ->method('get') 
     ->with('security.context') 
     ->will($this->returnValue($service)); 

希望這有助於

編輯:

你弄髒了錯誤Token對象。替補:

// I create a Token for mock getUser() 
    $token = $this->getMock('\Symfony\Component\Security\Core\Authentication\Token'); 

有了:

// I create a Token for mock getUser() 
    $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'); 
+0

感謝@Matteo!但現在,我在下一步中遇到錯誤:'.PHP致命錯誤:調用未定義的方法Mock_Token_66794207 :: getUser()'。你在我的代碼中看到錯誤嗎? – Gura 2014-10-09 08:56:36

+0

http://stackoverflow.com/questions/12599957/undefined-method-on-mock-object-implementing-a-given-interface-in-phpunit幫助我呢! – Gura 2014-10-09 09:11:24

+1

我複製你的問題並修復它!我編輯我的回覆。 – Matteo 2014-10-09 09:21:58