Testing Zend Framework controllers in isolation

What I do is I have my con­trollers fetch all their depen­den­cies from the boot­strap and/or front con­troller. The most com­mon exam­ple is to pull the db resource from the boot­strap:

// in controller
$db = $this->getInvokeArg('bootstrap')->getResource('db');

But I also take it a step fur­ther. For exam­ple, if I’m using data map­pers, I have the action con­troller check the front con­troller for the data map­per I need:

// in controller
$postsMapper = $this->getInvokeArg('posts_mapper');

I then update your unit test to inject the posts map­per with a stub:

// in unit test
$this->frontController->setParam('posts_mapper', $stubPostsMapper);

How­ever, that invoke arg won’t exist in pro­duc­tion, so I wrap that call in an if state­ment a la “lazy load­ing” style:

if (null === ($postsMapper = $this->getInvokeArg('posts_mapper'))) {
$postsMapper = new Default_Model_Mapper_Posts();
}

What this does is it allows me to stub in my stub posts map­per in my unit tests while let­ting the con­troller lazy-load the real one in production.

An alter­na­tive is to use Zend_Registry, but I find this to be a bit cleaner with­out the sta­tic calls.


Hec­tor Virgen

Tags: ,

Leave a Comment

*

Get Adobe Flash playerPlugin by wpburn.com wordpress themes