如何测试上CakePHP2.0的添加功能(How can i test an Add functio

2019-06-25 07:55发布

我已被告知,我们也测试通过创建蛋糕喜欢添加/删除功能...

如果我有一个功能,像这样的,我怎么可以测试它,如果它没有任何回报,重定向或甚至一个看法? (ⅰ使用Ajax执行它)

public function add() {
        if ($this->request->is('post')) {
            $this->Comment->create();
            if ($this->Comment->save($this->request->data)) {
                $this->Session->setFlash(__('The comment has been saved'));
            } else {                
                $this->Session->setFlash(__('The comment could not be saved. Please, try again.'));
            }
        }
    }

谢谢

Answer 1:

public function add() {
        $this->autoRender = false;
        if ($this->request->is('post')) {
            $this->Comment->create();
            if ($this->Comment->save($this->request->data)) {
                echo json_encode(array('status' => 'ok'));
            } else {  
                echo json_encode(array('status' => 'fail'));              
            }
        }
    }


Answer 2:

这里有一个排序通用的方法来测试它。

function testAdd() {
  $Posts = $this->generate('Posts', array(
    'components' => array(
      'Session',
      'RequestHandler' => array(
        'isAjax'
      )
    )
  ));
  // simulate ajax (if you can't mock the magic method, mock `is` instead
  $Posts->RequestHandler
    ->expects($this->any())
    ->method('isAjax')
    ->will($this->returnValue(true));
  // expect that it gets within the `->is('post')` block
  $Posts->Session
    ->expects($this->once())
    ->method('setFlash');

  $this->testAction('/posts/add', array(
    'data' => array(
      'Post' => array('name' => 'New Post')
    )
  ));
  // check for no redirect
  $this->assertFalse(isset($this->headers['Location']));
  // check for the ajax layout (you'll need to change 
  // this to check for something in your ajax layout)
  $this->assertPattern('/<html/', $this->contents);
  // check for empty view (I've never had an empty view but try it out)
  $this->assertEqual('', $this->view);
}


文章来源: How can i test an Add function on CakePHP2.0