2012-05-22 86 views
0

我正在嘗試爲文章控制器測試非常簡單的添加動作。以下是我的代碼。我不明白爲什麼這不起作用。測試cakephp 2.1控制器的動作,如添加和編輯

$this->Articles->Article->hasAny 

應該爲我剛剛調用的admin_add操作和我剛剛添加的測試記錄返回true。然而它返回false;

class ArticlesControllerTestCase extends ControllerTestCase { 

    /** 
     * Test Admin Add 
     * 
     * @return void 
     */ 
     public function testAdminAdd() { 

      #define sample passing data 
      $sampleDataPass = array(
       'Article'=>array(
        'title'=>'---Test Article Add---', 
        'body'=>'---Test Article Add Body---', 
        'status_id'=>1, 
        'category_id'=>1, 
       ) 
      ); 

      #test passing data 
      $this->Articles->request->data = $sampleDataPass; 
      $this->testAction('admin/articles/add', array('data'=>$sampleDataPass)); 
      $this->assertEquals($this->Articles->Article->hasAny(array('Article.title'=>'---Test Article Add---')), true); #fails here 
      } 
    } 


class MastersController extends AppController { 
/** 
    * Admin Add 
    * Default admin add method for all controllers 
    * Adds a record to the models database table 
    * Not calling add action becase of __setRootUserId action 
    * @return void 
    */ 
    protected function _admin_add() { 
     if (!empty($this->request->data)) { 
      #save data 
      $this->{$this->modelClass}->create(); 
      if ($this->{$this->modelClass}->save($this->request->data)) { 
       return $this->Redirect->flashSuccess($this->modelClass.' saved.', isset($this->redirectSuccessUrl) ? $this->redirectSuccessUrl : array('action' => 'view', $this->{$this->modelClass}->id)); 
      } else { 
       return $this->Redirect->flashWarning($this->modelClass.' could not be saved.', isset($this->redirectWarningUrl) ? $this->redirectWarningUrl : null); 
      } 
     } 
     $this->_lists(); 
    } 
} 

class ArticlesController extends MastersController { 
    /** 
    * Admin Add 
    * @see controllers/MastersController::_admin_add() 
    * @return void 
    */ 
    public function admin_add(){ 
     parent::_admin_add();  
    } 
} 

回答

0

緩存$this->Article$this->controller(只會調用testAction後工作)。如果您之前需要調用它,則需要在執行任何操作之前調用$this->generate()以獲取控制器實例。