How can i test an Add function on CakePHP2.0

℡╲_俬逩灬. 提交于 2019-12-31 02:33:05

问题


I have been told that we have to test also the functions created by Cake like add/delete...

If i have a function like this one, how can i test it if it doesn't have any return, redirect or even a view? ( i use ajax to execute it)

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.'));
            }
        }
    }

Thanks


回答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'));              
            }
        }
    }



回答2:


Here's a sort of generic way to test it.

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


来源:https://stackoverflow.com/questions/10173506/how-can-i-test-an-add-function-on-cakephp2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!