Unit testing Zend Framework Models with PHPUnit

A new project created by the ZF command line tool (zf) will have a default IndexControllerTest in the tests folder. The test class inherits from Zend_Test_PHPUnit_ControllerTestCaseand provides a good example of how to test a controller.

Unfortunately the tests folder doesn’t come with any example of how to test a model. I’m guessing the reason for that is ZF doesn’t need to provide any code (class to extend) to help with that. In fact PHPUnit_Framework_TestCase is enough to perform a model unit testing.

The only problem one might come across is how to setup a test class to have at minimum autoloader at place. It can be achieved by initialising Zend_Application in the setUp() method.


/** 
 * tests/application/models/YourClassTest.php
 */
class Application_Model_YourClassTest  extends PHPUnit_Framework_TestCase {

    public function setUp() {

        $application = new Zend_Application(
            APPLICATION_ENV,
            APPLICATION_PATH . '/configs/application.ini' );
                
        $application->bootstrap('autoloader');
    
    }

    public function testSomething() {
        // some assertions
    }
}

Obviously you can bootstrap more than just the autoloader but that depends on your particular needs. For example I usually have to bootstrap: config, defaultModuleAutoloader, autoloader and propel.


$application->bootstrap('config')
            ->bootstrap('defaultModuleAutoloader')
            ->bootstrap('autoloader')
            ->bootstrap('propel');

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s