2012-05-13 29 views
3

我是通用的phpunit和單元測試新手。我試圖將一個大型應用程序轉換爲cakephp 2.0並對所有內容進行單元測試。CakePHP 2.1:使用Session :: read()製作模擬控制器

我想創建一個模擬對象,當$ this-> Session-> read('Auth.Account.id')被調用時,它返回144 ...這將給一個帳戶一個id有項目。

但是,我得到一個錯誤,因爲模擬似乎在各種beforeFilter調用中的其他Session :: read('AuthCode')調用中出錯;

期望失敗方法名稱爲等於當調用1周時間(s) 參數0爲調用SessionComponent ::讀(「校驗碼」)不匹配預期值。 失敗斷言兩個字符串相等。

就像我說的我是新來phpunit和單元測試...我做錯了什麼?

class PagesController extends MastersController { 
     public function support(){ 
     if($this->Session->read('Auth.Account.id')) { 
      $items = $this->Account->Items->find('list', array('conditions'=>array('Items.account_id'=>$this->Session->read('Auth.Account.id'))));   
     } 
     $this->set(compact('items')); 
    } 
} 


class PagesControllerTestCase extends CakeTestCase { 
     /** 
    * Test Support 
    * 
    * @return void 
    */ 
    public function testSupport() { 
     #mock controller 
     $this->PagesController = $this->generate('Pages', array(
      'methods'=>array('support'), 
      'components' => array(
       'Auth', 
       'Session', 
      ), 
     )); 

       #mock controller expects 
     $this->PagesController->Session->expects(
      $this->once()) 
       ->method('read') #Session:read() method will be called at least once 
       ->with($this->equalTo('Auth.Account.id')) #when read method is called with 'Auth.Account.id' as a param 
       ->will($this->returnValue(144)); #will return value 144 


     #test action 
     $this->testAction('support'); 
    } 
} 
+0

我我至少想正確的...是$這個 - > PagesController- >會話級>預計($這 - >一次()) - >方法( '讀') - >用( 'Auth.Account.id') - >將($這 - >的returnValue(144));是否僅在Session :: read('Auth.Account.id')被調用一次時返回144?當Session :: read('AuthCode')在beforeFilter調用中觸發時,它不會被觸發...對嗎?就像我說的我一般對phpunit和單元測試都是新手,但我認爲這樣做是對的,對吧? – devnull

回答

1

你應該訪問驗證會話變量與驗證組件,而不是會話組件。

而不是

if($this->Session->read('Auth.Account.id')) {

嘗試

if ($this->Auth->user('Account.id')) {

也是一樣的物品 - 找電話。

嘲笑Auth組件仍然是要走的路。

class PagesControllerTestCase extends CakeTestCase {

應該

class PagesControllerTestCase extends ControllerTestCase {

,然後在您的測試:

$PagesController = $this->generate('Pages', array(
    'methods'=>array('support'), 
    'components' => array(
     'Auth' => array('user') 
    ), 
)); 

$PagesController->Auth->staticExpects($this->exactly(2)) 
    ->method('user') 
    ->with('Account.id') 
    ->will($this->returnValue(144));