Unit tests for yii modules

Testing yii modules 

I was creating simple yii module (about which perhaps I will write later). Since last time I like TDD more and more I’ve decided to test it. But there is a problem I’d like to move all tests to [my_module]/tests and do not mix them with project tests.

I din’t find any good tutorial on this topic and decided to do it by myself.
Please note: I added only unit tests. But I believe it’s easy to add functional tests and you can do it by yourself. 

Ok let’s start first of all we create following test directory structure:

— test.php
— /fixtures
— /unit
— bootstrap.php
— phpunit.xml

As you see this is the copy of standard yii directory structure except some files. In fixtures and unit folders we will put fixtures and tests files as we do for standard yii tests. phpunit.xml also will leave the same. Of course you can customize it as you need.

<phpunit bootstrap="bootstrap.php" colors="true" converterrorstoexceptions="true" convertnoticestoexceptions="true" convertwarningstoexceptions="true" stoponfailure="false">

    <testsuite name="all tests">

In bootstrap.php we will change paths and comment WebTestCase.php including

 $appPath = realpath(dirname(__FILE__) . '/../../../');
 $config = $appPath . '/modules/pct/config/test.php';
 require_once($appPath . '/yii/framework/yiit.php');

And finally config.php

 $basePath = realpath(dirname(__FILE__) . '/../../..');

 return array(
     'basePath' => $basePath,

      'import' => array(
        // any other includings

             'basePath' => realpath(dirname(__FILE__) . '/../tests/fixtures'),
             // redefine basePath for module tests
             'connectionString' => 'mysql:host=;dbname=[test_db_name]',
             'username' => '',
             'password' => '',

I define the whole config but you can use test config from main application by

return CMap::mergeArray(

That’s it. Good testing for you guys and thank you.

Leave a Reply

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