Symfony 1.4 Action plus View Rendering PHPUnit Test
I wrote test case for executing action and rendering view test.
However testing action plus final rendering result is quite not easy because you need to understand how Symfony 1.4 framework handles web request and rendering model to view internally.
I have investigated in the framework a bit and found a solution.
Please see the test case example in the next section.
Code
<?php $basePath = dirname(__FILE__).'/../../../../apps/your_app_name/modules/'; $modulePaths = glob($basePath.'*', GLOB_ONLYDIR); foreach($modulePaths as $modulePath) { require_once $modulePath.'/actions/actions.class.php'; } class ActionsTest extends PHPUnit_Framework_TestCase { public function testActions() { // create stub web request $request = $this->createStubfWebRequest(); // action you would like to test. // you should pass module and action name refelctively $actions = new TargetActions($this->context, 'Target', 'index'); // execute action and render!! $this->executeAndRender($actions, $request); } /** * @var sfContext */ private $context; public function setUp() { $this->context = sfContext::createInstance(sfProjectConfiguration::getApplicationConfiguration("your_app_name","prod",false)); $this->context->set('actionStack', new sfActionStack()); } public function executeAndRender(sfActions $actions, sfRequest $request, $view=sfView::SUCCESS) { $this->context->set('request', $request); $this->context->getActionStack()->addEntry($actions->getModuleName(), $actions->getActionName(), $actions); // execute actions $actions->preExecute(); $actions->execute($request); $actions->postExecute(); // rendering view $controller = $this->context->getController(); $view = $controller->getView($actions->getModuleName(), $actions->getActionName(), $view); $view->execute(); $view->getAttributeHolder()->add($actions->getVarHolder()->getAll()); $view->render(); } // simulate get request private function createStubSfWebRequest() { $stubRequest = $this->getMockBuilder('sfWebRequest')->disableOriginalConstructor()->getMock(); $stubRequest ->expects($this->any()) ->method('isMethod') ->will($this->returnCallback(function($o){ $args = func_get_args(); return $args[0] === 'get'; })); $stubRequest ->expects($this->any()) ->method('getMethod') ->will($this->returnValue('GET')); $stubRequest ->expects($this->any()) ->method('getGetParameters') ->will($this->returnValue(array())); return $stubRequest; } }
コメント