Testing Zend Framework controllers in isolation

What I do is I have my controllers fetch all their dependencies from the bootstrap and/or front controller. The most common example is to pull the db resource from the bootstrap:

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

But I also take it a step further. For example, if I’m using data mappers, I have the action controller check the front controller for the data mapper I need:

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

I then update your unit test to inject the posts mapper with a stub:

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

However, that invoke arg won’t exist in production, so I wrap that call in an if statement a la “lazy loading” 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 mapper in my unit tests while letting the controller lazy-load the real one in production.

An alternative is to use Zend_Registry, but I find this to be a bit cleaner without the static calls.


Hector Virgen

Leave a Reply

Your email address will not be published. Required fields are marked *