测试重定向CakePHP 2.0

Alv*_*aro 4 testing redirect unit-testing cakephp cakephp-2.0

我一直在看菜谱上的一些例子,但我不明白:http: //book.cakephp.org/2.0/en/development/testing.html#a-more-complex-example

如何在像这样的删除操作中测试重定向?

public function delete($id = null){         
        $this->Comment->id = $id;
        if (!$this->Comment->exists()) {
            throw new NotFoundException(__('Invalid comment'));
        }
        if ($this->Comment->delete()) {         
            $this->Session->setFlash(__('Comment deleted'));
            return $this->redirect(array('controller' => 'posts', 'action' => 'view', $idPost));
        }
        $this->Session->setFlash(__('Comment was not deleted'));
        return $this->redirect(array('controller' => 'posts', 'action' => 'view', $idPost));        
    }
}
Run Code Online (Sandbox Code Playgroud)

重定向调用后测试停止,因此它甚至不打印此回声:

public function testDelete(){       
    $result = $this->testAction("/comments/delete/1");
    echo "this is not printed";
    print_r($this->headers);        
}
Run Code Online (Sandbox Code Playgroud)

jer*_*ris 7

测试删除操作应该与测试任何其他操作相对相同.您的测试用例可能看起来像这样.

// notice it extends ControllerTestCase
class PostsControllerTest extends ControllerTestCase {

    function testDelete() {
      $this->testAction('/posts/delete/1');
      $results = $this->headers['Location'];
      // your OP code redirected them to a view, which I assume is wrong
      // because the item would be deleted
      $expected = '/posts/index';
      // check redirect
      $this->assertEquals($results, $expected);

      // check that it was deleted
      $this->Posts->Post->id = 1;
      $this->assertFalse($this->Posts->Post->exists());
    }

}
Run Code Online (Sandbox Code Playgroud)

当然,这只是检查明显的.您还可以检查会话并编写一个期望异常的测试.如果它还没有达到测试用例的结尾或继续,那么还有其他事情正在发生.

您可以使用generate方法生成简单的模拟ControllerTestCase.

function testDelete() {
  $Posts = $this->generate('Posts', array(
    'components' => array(
      'Email' => array('send'),
      'Session'
    )
  ));
  // set ControllerTestCase to use this mock
  $this->controller = $Posts;

  $this->testAction('/posts/some_action_that_sends_email');
}
Run Code Online (Sandbox Code Playgroud)

以上将首先生成在测试期间使用的PostsController的模拟.它还send()在EmailComponent和整个SessionComponent上模拟该方法.

有关模拟的更多信息:http://www.phpunit.de/manual/3.0/en/mock-objects.html

有关以下内容的更多信息generate():http://book.cakephp.org/2.0/en/development/testing.html#using-mocks-with-testaction