1

我正在测试一个用 cake 制作的应用程序,在测试 add 方法时发现了一个问题。实际上的问题是,每当我想测试在数据库上保存数据时,在制作了与请求一起发送的样本数据后,我发现该数据保存在数据库上,但只设置了 id 属性。其他字段为空。

这是我要测试的方法:

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();

}

请注意,如果我运行此测试,我将在 db 上有一个额外的字段,并且因为表的 id 是自动递增的,所以我无法取回 id 以删除该条目。
现在的问题是:有什么方法可以在不实际保存数据的情况下测试数据库保存?

谢谢!

4

1 回答 1

0

为了防止保存数据,您需要使用 Fixtures。以下是基于您使用的 CakePHP 版本的文档:

确保使用测试数据库,否则您会发现在每次测试运行后,您的表都会被删除。

于 2013-02-18T20:06:35.607 回答