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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * 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.
1 2 3 4 |
$application->bootstrap('config') ->bootstrap('defaultModuleAutoloader') ->bootstrap('autoloader') ->bootstrap('propel'); |