2013-01-04 104 views
3

我正在嘗試編寫和測試控制器操作。以下是我有:Cakephp 1.3模擬身份驗證

App::import('Component', 'Auth'); 
App::import('Controller', 'Goals'); 

class GoalControllerTest extends CakeTestCase { 

    function startCase() { 
      echo '<h1>Starting Test Case</h1>'; 
      $this->Goals = new TestGoalsController(); 
      $this->Goals->constructClasses(); 
      $this->Goals->Component->initialize($this->Goals); 
    } 

    function endCase() { 
      unset($this->Goals); 
      ClassRegistry::flush(); 
      echo '<h1>Ending Test Case</h1>'; 
    } 

    function startTest($method) { 
      echo '<h3>Starting method ' . $method . '</h3>'; 
      //$this->GoalsController = new TestGoalsController(); 
      Mock::generate('AuthComponent'); 
      $this->Goals->Auth = new MockAuthComponent(); 
    } 

    function endTest($method) { 
      echo '<hr />'; 
    } 

    function testSetHomepage() { 
      //get goal for test 
      $sql = "SELECT id FROM goals limit 1"; 
      $goal = $this->Goals->Goal->query($sql); 
      $this->Goals->params = Router::parse('/goals/setHomepage/'); 
      $this->Goals->beforeFilter(); 
      $this->Goals->Component->startup($this->Goals); 
      $this->Goals->params['url']['goal_id'] = $goal[0]['goals']['id']; 
      $this->Goals->params['url']['set_to'] = 1; 
      $this->Goals->setHomepage(); 

      //Mock Auth 
      $this->Goals->Auth->setReturnValue('user', 1); 


      //check the set 
      $sql = "SELECT GoalOnHome.goal_id FROM goals_users as GoalOnHome WHERE GoalOnHome.goal_id = '" . $this->Goals->params['url']['goal_id'] . "' limit 1"; 
      $result = $this->Goals->Goal->query($sql); 

      $expected = false; 
      $this->assertEqual(empty($result), $expected); 
      unset($this->Goals->params['url']); 
    } 
} 

我試圖嘲弄認證組件,當我運行測試我得到這個錯誤:

Unexpected PHP error [Undefined property: MockAuthComponent::$enabled] severity [E_NOTICE] in

有人可以幫助我與我在做什麼這裏錯了嗎?

+0

我被模擬genereate移動到擺脫未定義的屬性錯誤:功能startCase(){ 回聲「

開始測試案例

」; $ this-> Goals = new TestGoalsController(); Mock :: generate('AuthComponent'); $ this-> Goals-> Auth = new MockAuthComponent(); $ this-> Goals-> constructClasses(); $ this-> Goals-> Component-> initialize($ this-> Goals); }但我知道得到這個錯誤:致命錯誤:調用未定義的方法AuthComponent :: setReturnValue()in – rstewart

回答

0

我最近有同樣的問題。我通過簡單地在Mock對象上設置屬性來修復它。另外,我爲startup -method配置了返回值 - 否則,模擬認證將不起作用。

function startTest() { 
    // Set up controller etc. 
    // ... 
    $this->Goals->Auth = new MockAuthComponent(); 
    $this->Goals->Auth->enabled = true; // Should solve your error 
    $this->Goals->Auth->setReturnValue('startup', true); 
}