2013-11-22 57 views
0

我一直在嘗試理解「模擬數據庫」一段時間,但並沒有完全理解。我擁有的是一個Symfony2項目。我有一個控制器,我需要測試它。因此即時通訊使用PHPUnit測試。除了嘲笑數據庫部分之外,我設法瞭解其他所有內容。控制器所做的是對用戶進行身份驗證。爲此,我使用了數據庫,但我不知道如何進行相應的測試和配置。這是我已經試過了,Symfony2 PHPUnit嘲笑數據庫問題

控制器:

class LoginController extends Controller 
{ 
    public function indexAction(Request $request) 
    {  
     $em = $this->getDoctrine()->getManager(); 
     $usersRepo = new UsersRepository($em); 

      $form = $this->createForm(new LoginForm()); 

      $form->handleRequest($request); 

      if ($form->isValid()) { 

       $request_data = $request->get($form->getName()); 

       $useremail= $request_data['useremail'];    
       $password = $request_data['password']; 

       $user = $usersRepo->userAuthenticate($useremail, $password); 

       if($user) 
       {          
        $session = $this->getRequest()->getSession(); 
        $session->set('user', $user); 
        return $this->redirect($this->generateUrl('homepage'));    
       } 
       else 
       {     
        $this->get('session')->getFlashBag()->set('notice',’Login Failed’);      
       } 
      } 

     return $this->render('TestBundle:Default:login.html.twig', array('form' => $form->createView())); 
    } 

庫是「UsersRepository」和實體是「用戶」。有了這些細節我寫了一個測試控制器。

class LoginControllerTest extends WebTestCase { 
    public function testlogoutActionValidSessionExist() { 

     $employee = $this->getMock('\Test\DABundle\Entity\Users'); 
     $employee->expects($this->once()) 
      ->method('userAuthenticate') 
      ->with($this->equalTo(‘[email protected]'), $this->equalTo('testworld'));; 

     // Now, mock the repository so it returns the mock of the employee 
     $employeeRepository = $this->getMockBuilder('\Doctrine\ORM\ UsersRepository) 
      ->disableOriginalConstructor() 
      ->getMock(); 
     $employeeRepository->expects($this->once()) 
      ->method('find') 
      ->will($this->returnValue($employee)); 

     // Last, mock the EntityManager to return the mock of the repository 
     $entityManager = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager') 
      ->disableOriginalConstructor() 
      ->getMock(); 
     $entityManager->expects($this->once()) 
      ->method('getRepository') 
      ->will($this->returnValue($employeeRepository)); 

     $client = static::createClient();    
     $client->request("GET", "/user/login/"); 

     $this->assertEquals(200 , $client->getResponse()->getStatusCode()); 
    } 
} 

所以在這個測試控制器香港專業教育學院將代碼從網絡,但試圖瞭解得到這個工作。請看看我做錯了什麼或有什麼建議可以幫助你做到這一點。提前謝謝你

回答

2

我不認爲你需要實際'模擬'數據庫,而是生成一個臨時的運行你的測試。

要創建臨時數據庫,請將symfony配置爲使用SQLite。然後將一些燈具加載到新數據庫中,並在控制器上對這些燈具執行測試。

該框架處理之後的數據庫刪除。

我使用以下包來協助自動加載夾具。

https://github.com/liip/LiipFunctionalTestBundle

在config_test.yml設置爲SQLITE的連接。

doctrine: 
    dbal: 
     default_connection: default 
     connections: 
      default: 
       driver:  pdo_sqlite 
       path:  %kernel.cache_dir%/test.db 
       charset: UTF8 
+0

好的,我會嘗試這種方法。謝謝!但是,你是否知道通過嘲笑數據庫來回答我的問題? –