Developerium
Developerium

Reputation: 7265

Yii unit tests, Constants in yii

I'm writing unit tests in Yii, and I need a way to understand I'm in test mode(for default scopes and ..).I've defined a constant in index-test.php. like:

defined('YII_TEST_MODE') or define('YII_TEST_MODE',true);

in my model:

if(YII_TEST_MODE){ ...

but in my code when I'm checking this it show this error:

Use of undefined constant YII_TEST_MODE - assumed 'YII_TEST_MODE'

Is there a better way to know tell yii you are in test mode? and also am I using wrong syntax?

Upvotes: 0

Views: 275

Answers (2)

Zack Newsham
Zack Newsham

Reputation: 2982

you want to be very careful about using if(TEST) in your code, the purpose of unit tests is to test the actual code that will be used for a specific function/class.

Doing it the way you are, only ensures that the code works in test mode, not in real mode - which defies the point.

If you follow the paradigm that each functional class should have its own set of unit tests, then mock the other classes that it interacts with, rather than doing specific actions when in test mode.

For example, if you are testing the functionality of your model class, and you dont want to save data to a database, you can instead mock the database connection with one that does not actually store any data.

That being said, if you note your config folder, you will likely see that you have a main.php and a test.php. What you can do is define a variable "is_test" as follows:

'params'=>array(
  'is_test'=>false
)

you put that in your main.php, and in your test.php you set it to true. Then you can check Yii::app()->params["is_test"]

Upvotes: 1

Developerium
Developerium

Reputation: 7265

I was wrong thinking that index-test.php is running unit tests, actually /protected/tests/bootstrap.php initializes test mode.

but I still don't know index-test.php is good for?

Upvotes: 0

Related Questions