2008年10月1日星期三

[fw-mvc] Zend_Test_Controller_Action_Helper_ViewRenderer

We recently wanted to test our ZF controllers in isolation from the views and
from the front-controller plumbing. It's been extremely helpful in writing
and testing controller code without having to finalize views for them.

In order to do this, we used a stub ViewRenderer which does nothing but
register a default Zend_View object to the controller. We can then construct
the controllers with request fixtures, invoke the controller action methods
directly, and then assert against the variables assigned to the view in
course of the action method.

I think this tactic may be useful enough to consider incorporating into
Zend_Test? Here's example code ...

class Sfx_Controller_Action_Helper_TestViewRenderer extends
Zend_Controller_Action_Helper_ViewRenderer
{
public function initView()
{
if (null === $this->view) {
$this->setView(new Zend_View());
}
// Register view with action controller (unless already registered)
if ((null !== $this->_actionController) && (null ===
$this->_actionController->view)) {
$this->_actionController->view = $this->view;
}
}
}

class Sfx_Controller_TestCase extends Sfx_TestCase
{
protected $_request;
protected $_response;
protected $_controller;

public function setUp()
{
parent::setUp();

// set up smarty view and restful view helper
$viewRenderer = new Sfx_Controller_Action_Helper_TestViewRenderer();
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);

$this->_request = new Zend_Controller_Request_Http();
$this->_response = new Zend_Controller_Response_Cli();

}
}

class ProjectControllerTest extends Sfx_Controller_TestCase
{
public function setUp()
{
parent::setUp();
$this->_controller = new ProjectController($this->_request,
$this->_response);
}

public function test_indexAction_fetches_all_projects()
{
$this->_controller->indexAction();
$this->assertNotNull($this->_controller->view->projects);
$this->assertEquals(26,count($this->_controller->view->projects));
}
public function test_indexAction_new_since_fetches_only_new_projects()
{
$this->_request->setParam('new_since',1205880839);
$this->_controller = new ProjectController($this->_request,
$this->_response);
$this->_controller->indexAction();
$projects = $this->_controller->view->projects;
$this->assertEquals(3,count($projects));
foreach($projects as $project){
$this->assertGreaterThan(1205880839, $project->register_time);
}
}
}
--
View this message in context: http://www.nabble.com/Zend_Test_Controller_Action_Helper_ViewRenderer-tp19761376p19761376.html
Sent from the Zend MVC mailing list archive at Nabble.com.

没有评论: