Skip to content

Instantly share code, notes, and snippets.

@rapzo
Forked from mehlah/ArticleControllerTest.php
Created May 15, 2013 00:22
Show Gist options
  • Save rapzo/5580796 to your computer and use it in GitHub Desktop.
Save rapzo/5580796 to your computer and use it in GitHub Desktop.
<?php
namespace app\tests\cases\controllers;
use app\tests\mocks\MockArticlesController;
use app\tests\mocks\action\MockControllerRequest as Request; //Mocking the Request
class ArticlesControllerTest extends \lithium\test\Unit {
protected $_controller;
public function setUp() {
$this->_controller = new MockArticlesController();
}
public function tearDown() {
Session::delete('FlashMessage'); //avoid session flash messages after running tests
}
public function testIndexList() {
$this->_controller->index();
// or $this->_controller(null, array('action' => 'index', 'args' => array()));
// that make use of PHP's callable syntax and yield to call `Controller::__invoke()` for dispatching requests to action methods.
// $this->_controller->__invoke(null, array('action' => 'index', 'args' => array()));
$render = $this->_controller->access('_render');
$viewVars = $render['data'];
$this->assertTrue(isset($viewVars['test']),"The index 'test' isn't set");
$this->assertEqual("test",$viewVars['test'],"The string should be 'test'");
}
public function testFoo() {
$request = new Request();
$articlesController = new MockArticlesController(compact('request')); //You can give it a custom request with data for example
$response = $articlesController->foo();
// Test Flash message is set (reading from session)
$result_flash = Session::read('FlashMessage.default', array('name' => 'default'));
$expected_flash = array('message' => 'No article found', 'atts' => array());
$this->assertEqual($expected_flash, $result_flash);
// Test a redirection to Articles::index
$this->assertEqual($response->body(), '');
$headers = array('Location' => '/articles');
$this->assertEqual($response->headers, $headers);
}
}
<?php
namespace app\controllers;
class ArticlesController extends \lithium\action\Controller {
public function index() {
$this->set(array('test' => 'test'));
}
public function foo() {
// suppose setting a flash message and redirection for example
}
}
<?php
namespace app\tests\mocks;
use app\controllers\ArticlesController;
class MockArticlesController extends ArticlesController {
protected $_classes = array(
'media' => 'lithium\net\http\Media',
'router' => 'lithium\net\http\Router',
'response' => 'app\tests\mocks\action\MockControllerResponse'
);
public function access($varName) {
return $this->{$varName};
}
}
<?php
namespace app\tests\mocks\action;
class MockControllerResponse extends \lithium\action\Response {
public $hasRendered = false;
public function render() {
$this->hasRendered = true;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment