2011/12/21

Unit tests for yii modules

Testing yii modules 

we moved here http://radzserg.com/2011/12/21/unit-tests-for-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:

/config
    -- test.php
/tests
    -- /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">
        <directory>./</directory>
    </testsuite>
</phpunit>


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

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

require_once($appPath . '/yii/framework/yiit.php');
//require_once(dirname(__FILE__).'/WebTestCase.php');

Yii::createWebApplication($config);


And finally config.php


<?php

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

return array(
    'basePath' => $basePath,

     'import' => array(
        'application.modules.[my_module].models.*',
        'application.modules.[my_module].components.*',

        // any other includings
    ),

    'components'=>array(
        'fixture'=>array(
            'class'=>'system.test.CDbFixtureManager',
            'basePath' => realpath(dirname(__FILE__) . '/../tests/fixtures'),

             // redefine basePath for module tests
        ),
        'db'=>array(
            'connectionString' => 'mysql:host=127.0.0.1;dbname=[test_db_name]',
            'username' => '',
            'password' => '',
        ),
    ),
);


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

return CMap::mergeArray(
require(dirname(__FILE__).'../../../config/test.php'),
        array()



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

No comments:

Post a Comment