2012-09-26 34 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的您正在使用的文档:

确保使用测试数据库或运行每次测试后,你会发现,你的表将被丢弃。