【问题标题】:Testing an add method with cakephp and phpunit用 cakephp 和 phpunit 测试 add 方法
【发布时间】:2012-09-18 03:01:41
【问题描述】:

我正在测试一个用 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 以删除该条目。
现在的问题是:有什么方法可以在不实际保存数据的情况下测试数据库保存?

谢谢!

【问题讨论】:

  • 另一件事:如果我在 add 方法中取消注释 $this->redirect 行,则测试不起作用。

标签: php cakephp phpunit


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-11-28
    • 2015-11-28
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 2017-08-14
    • 2014-02-13
    相关资源
    最近更新 更多