Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii: Unit test models without database server

Tags:

yii

What is the preferred/correct way to perform unit tests against Yii models without having access to a database server (or other external resources)? All of the unit testing documentation I have found suggests that you have to have an active database server, but obviously that is not ideal for unit testing.

For what it is worth, here is my config/test.php and my bootstrap.php:

<?php

return CMap::mergeArray(
    require(dirname(__FILE__).'/main.php'),
    array(
        'components'=>array(
            'fixture'=>array(
                'class'=>'system.test.CDbFixtureManager',
            ),
        ),
    )
);

and

<?php

// change the following paths if necessary
$yiit=dirname(__FILE__).'/../../yii-1.1.13.e9e4a0/framework/yiit.php';
$config=dirname(__FILE__).'/../config/test.php';

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

Yii::createWebApplication($config);

and when I run the tests I get:

CDbException: CDbConnection.connectionString cannot be empty.

2 Answers

Yii authors have a misleading name for their integration tests. They call them "unit" ones. In fact, if you need to have a connection to the DB server, it's not unit tests anymore.

If you want to test your ActiveRecords in isolation, first you should implement a fake CDbConnection which will map to some in-memory datasets (or to filesystem-based ones). Yii does not come with such a thing built-in.

After that, you just do CActiveRecord::$db = new FakeDbConnection() in your bootstrap.php and I believe you will not have to even change your existing test suite at all.

like image 95
hijarian Avatar answered Apr 30 '26 18:04

hijarian


The only alternative i can think of, would be to use SQLite and supply a DB file with your unit tests. But this again has some limitations, e.g. it does not support foreign keys and some other features from a "real" DB. After all if you want to test models, you need some sort of DB.

like image 39
Michael Härtl Avatar answered Apr 30 '26 19:04

Michael Härtl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!