Skip to content

Instantly share code, notes, and snippets.

@oppara
Created April 22, 2011 14:34
Show Gist options
  • Save oppara/936787 to your computer and use it in GitHub Desktop.
Save oppara/936787 to your computer and use it in GitHub Desktop.
cakephp controller test
<?php
// テスト対象のコントローラ
// app/controllers/hoge_controller.php
class HogeController extends AppController {
var $name = 'Hoge';
var $uses = array('Hoge');
function index() {
$this->Hoge->recursive = 0;
$this->set('hoge', $this->paginate());
return 1;
}
function foo() {
// リダイレクト!!
$this->redirect(array('action' => 'index'));
}
function view($id = null) {
$this->set('moge', $id);
}
}
?>
<?php
// テスト用のコントローラ
// app/tests/test_app/controllers/test_hoge_controller.php
App::import('Controller', 'Hoge');
class TestHogeController extends HogeController {
var $redirectUrl;
function redirect( $url, $status = null, $exit = true ) {
$this->redirectUrl = $url;
}
}
?>
<?php
// コントローラ用テストケース
// app/tests/cases/controllers/controller_test_case.php
define('TEST_APP', TESTS . 'test_app' . DS);
define('TEST_CONTROLLERS', TEST_APP . 'controllers' . DS);
class ControllerTestCase extends CakeTestCase {
function setUp() {
App::build(array('controllers' => TEST_CONTROLLERS));
}
// CakeTestDispatcher内のフック
function startController(&$controller, $params = array()) {
$this->start_controller = $controller;
parent::startController($controller, $params);
}
// CakeTestDispatcher内のフック
function endController(&$controller, $params = array()) {
$this->end_controller = $controller;
parent::endController($controller, $params);
}
function asertRedirect($expected) {
$results = $this->end_controller->redirectUrl;
$this->assertIdentical($results, $expected);
}
}
?>
<?php
// テスト
// app/tests/cases/controllers/hoge_controller.test.php
require_once(dirname(__FILE__) . '/controller_test_case.php');
class HogeControllerTestCase extends CakeTestCase {
var $fixtures = array(
'app.hoge',
);
function startTest() {
Router::connect('/hoge/', array('controller' => 'test_hoge'));
Router::connect('/hoge/:action/*', array('controller' => 'test_hoge'));
// 直にコントローラを扱う場合
// App::import('Controller', 'TestHoge');
// $this->Hoge = &new TestHogeController();
// $this->Hoge->constructClasses();
// $this->Hoge->Component->initialize($this->Hoge);
}
function endTest() {
// unset($this->Hoge);
ClassRegistry::flush();
}
// redirectのテスト
function testFoo() {
$this->testAction('/hoge/foo');
$this->assertRedirect(array('action' => 'index'));
}
function testIndex() {
$results = $this->testAction('/hoge/', 'vars');
$this->assertTrue(isset($results['hoge']));
$results = $this->testAction('/hoge', 'result');
$this->assertIdentical($results, 1);
}
function testView() {
$results = $this->testAction('/hoge/view/1', 'vars');
$this->assertIdentical( $results, array( 'moge' => '1') );
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment