Marcito:
I only recently started using unit testing so I’m no expert, but here’s what I know…
-
Make sure you have installed PHPUnit correctly for your environment: Linux/Windows, under NetBeans or remote server, etc. I use NetBeans for Windows but test/deploy on a remote CentOS 5 server. Also make sure that your application has been configured for unit testing as explained in the Yii Guide.
-
Let’s say I have a simple Users model and I want to test one set of validation rules:
class Users extends CActiveRecord
{
...
public function rules()
{
return array(
array('username', 'required', 'on'=>'insert', 'message'=>Yii::t('app','Campo es obligatorio.')),
array('username', 'length', 'min'=>5, 'max'=>32, 'message'=>Yii::t('app','Debe tener entre 5 y 32 caracteres.')),
array('username', 'match', 'pattern'=>'/^[\p{L}\p{N}_]+$/u', 'message'=>Yii::t('app','Alfanumérico y subrayado (_) solamente.')),
array('username', 'filter', 'filter'=>'strtolower'),
array('username', 'unique', 'message'=>Yii::t('app','Usuario previamente registrado - escoja otro diferente.')),
...
}
...
}
- Next, under protected/tests/unit I have UsersTest.php:
class UsersTest extends CDbTestCase
{
/**
* @dataProvider provider
*/
public function testValidate($a)
{
$u = new Users;
$u->setAttributes(array(
'username'=>$a,
));
$this->assertTrue($u->validate());
}
public function provider()
{
return array(
array(''), // no username
array('A'), // username too short
array('0123456789012345678901234567890123456789'), // username too long
array('A!B@C#D$'), // username non alphanumeric
array('admin'), // username not unique
array('test_user'), // pass test
);
}
}
- Finally run phpunit UsersTest.php and watch the results.
You can expand on this by testing your own functions (the example above is for CModel.validate(), a Yii function but it helped me find an error in the match regex), both for input and returned values. It can get way more sophisticated by using fixtures and other stuff, but I’m still learning it. I highly recommend reading the PHPUnit manual for more information.
Good luck.