2012-09-26 35 views
1

我正在測試用蛋糕做的應用程序,並且在測試添加方法時發現問題。問題實際上是,無論何時我想測試在數據庫上保存數據,在發送樣本數據與請求發送後,我發現數據保存在數據庫中,但僅設置了id屬性。其他字段爲空。使用cakephp和phpunit測試添加方法

這是我想測試方法:

public function admin_add() { 
    if ($this->request->is('post')) { 
     debug($this->request->data); 
     $this->Item->create(); 
     if ($this->Item->save($this->request->data)) { 
      $this->Session->setFlash(__('The item has been saved')); 
      //$this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The item could not be saved. Please, try again.')); 
     } 
    } 
    $products = $this->Item->Product->find('list'); 
    $attributes = $this->Item->Attribute->find('list'); 
    $this->set(compact('products', 'attributes')); 
} 

這是我的測試:

public function testAdmin_add(){ 

$this->Items->request->params['action'] = 'admin_add'; 
$this->Items->request->params['url']['url'] = 'admin/items/add'; 
$data = array(
    'Item' => array(
    'product_id' => 1, 
    'attribute_id' => 9, 
    'title' => 'test_item', 
    'code' => 1, 
    'in_stock' => 1, 
    'batched_stock'=> 1, 
    'allocated' => 0, 
), 
); 

    $this->Collection = $this->getMock('ComponentCollection'); 
    $this->Items->Session = $this->getMock('SessionComponent', array('setFlash'), array($this->Collection)); 

    $this->Items->Session->expects($this->once()) 
     ->method('setFlash') 
     ->with(__d('items', 'Se ha guardado el item')); 


$this->__setPost($data); 

$this->Items->admin_add(); 

} 

注意,如果我運行這個測試我對數據庫的額外領域,因爲表的ID是自動增量我不能讓ID回來刪除該條目。
現在的問題是:有沒有什麼辦法可以測試DB保存而不實際保存數據呢?

謝謝!

+0

另一件事:如果我在add方法中取消$ this-> redirect行的註釋,則測試不起作用。 –

回答

0

要防止保存數據,您需要使用Fixtures。這是基於什麼版本的CakePHP的您正在使用的文檔:

確保使用測試數據庫或運行每次測試後,你會發現,你的表將被丟棄。