Professional Documents
Culture Documents
PHP Unit Testing in Yi I
PHP Unit Testing in Yi I
Types of tests
Functional test 1
Integration test 1
Unit test 1
Integration test 2
Unit test 2
Unit test 3
Code
Unit test 4
Controllers/Views
Functional test 1
Integration test 1
Integration test 2
Models
Unit test 1
Unit test 2
Unit test 3
Unit test 4
The states and the dependencies in controllers/views makes unit testing completely useless from a
server-side point of view.
Not true when considering javascript testing and other front-end behaviour/functionality which can
be done in other ways
Enters PHPUnit
PHPUnit help you deal with unit and
integration tests. http://www.phpunit.de/
Provides everything needed for any type of
test.
Produces reports in different formats (also for
code coverage).
Yii provides the functionality to integrate and
automate PHPUnit without worrying too much
about configuration.
unit/
fixtures/
fixtures directory
phpunit.xml
bootstrap.php
Setup a test DB
In protected/tests/bootstrap.php :
$config=dirname(__FILE__).'/../config/test.php';
In protected/config/test.php :
'db'=>array(
'connectionString' => 'mysql:host=localhost;
dbname=myproject_test',
),
// tests/unit/doodleTest.php
class DoodleTest extends DBbTestCase
{
//...
/**
* Test getImageSrc returns what
* has been passed to setImageSrc
*/
public function
testGetImageSrcRerturnsWhatHasBeenPassedToSetImageSrc() {
$model = new Doodle();
$expectedImageSrc = 'Something';
$model->imageSrc = $expectedImgSrc;
$this->assertEquals(
$expectedImgSrc,
$model->imageSrc
);
$this->_imageSrc = $data;
}
public function getImageSrc() {
return $this->_imageSrc;
}
//...
}
}
//...
}
//...
/**
* Test getImageSrc returns what has been passed to
setImageSrc
*
* @dataProvider imgSrcDataProvider
*/
public function
testGetImageSrcRerturnsWhatHasBeenPassedToSetImageSrc(
$expectedImgSrc
) {
$model = new Doodle();
/**
* Data Provider for getImageSrc / setImageSrc
*
* @return array
*/
public function imgSrcDataProvider() {
return array(
array(null),
array('some random text'),
array(0),
array(-1)
);
}
//...
}
Yii Fixtures
Flexible and useful way to deal with a mutable set of data.
Defined in protected/tests/fixtures/<lowercase-tablename>.php
Contains a return statement of an array of arrays.
Each first level array is a row. Each row can be key
indexed.
Setup at the top of the test Class with:
public $fixtures = array(
'users' => 'User', // <generic_name> => <table_name>
);
Fixtures uses
Class UserTest extends CDbTestCase
{
public $fixtures = array(
'users' => 'User',
);
/**
* @dataProvider expectancyDataProvider
*/
public function testUserExpectancyReturnsTheExpectedValue(
$expectedExpectancyValue
) {
$user = new User();
$user->setAttributes($this->users['simpleUser']);
$this->assertEquals(
$expectedExpectancyValue,
$user->calculateUserExpectancy()
);
}
Thank you!