【问题标题】:How can i test an Add function on CakePHP2.0如何在 CakePHP 2.0 中测试 Add 函数
【发布时间】:2012-04-16 11:48:44
【问题描述】:

有人告诉我,我们还必须测试 Cake 创建的函数,例如添加/删除...

如果我有这样的功能,如果它没有任何返回、重定向甚至视图,我该如何测试它? (我使用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.'));
            }
        }
    }

谢谢

【问题讨论】:

    标签: unit-testing cakephp testing cakephp-2.0 add


    【解决方案1】:

    这是一种通用的测试方法。

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

    【讨论】:

      【解决方案2】:
      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'));              
                  }
              }
          }
      

      【讨论】:

      • 谢谢老兄!但是……这不是比回声更好吗? $this->response->body(json_encode(array('status' => 'ok')));那就正确解码吧。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 2017-12-15
      • 2012-04-22
      • 1970-01-01
      • 2017-10-14
      相关资源
      最近更新 更多