PHP Unit Testing in Yii

22,601 views

Published on

Slides of the 5th meeting talk of the Yii London Meetup.

Published in: Technology, Education

PHP Unit Testing in Yii

  1. 1. PHP Unit Testingin YiiHow to start with TDD in Yiiby Matteo Peach PescarinTwitter: @ilPeach13/06/2013 - Yii London Meetup
  2. 2. What is this presentation about?● Quick introduction to TDD and Unit Testing● How to Unit Test? Types of Tests● PHPUnit and Yii● Write tests and Database interactions● Fixtures● Other features● Command line use● Few links.PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  3. 3. Test Driven Development (TDD)"encourages simple design and inspiresconfidence" - Kent BeckRe-discovered in 2004, is related to the test-first concept from eXtreme Programming.Works with any Agile methodology, but can beapplied in any context.Also useful when dealing with legacy code thatwasnt developed with such ideas in mind.Used as a way to document code by examples.PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  4. 4. What is Unit Testing?Its not about bug finding (theres no way thiscan be proved to be true).Its about designing software componentsrobustly.The behaviour of the units is specified throughthe tests.A set of good unit tests is extremely valuable!A set of bad unit tests is a terrible pain!PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  5. 5. Some tips to write Unit TestsThey must be isolated from each other:● Every behaviour should be covered by one test.● No unnecessary assertions (TDD: one logical assertionper test)● Test one code-unit at a time (this should force you writenon-overlapping code, or use IoC, Inversion of Control)● Mock external services and states (without abusing)● Avoid preconditions (although it might be usefulsometimes)Dont test configuration settings.Name your tests clearly and consistently.PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  6. 6. Types of testsUnit test 1 Unit test 2Integration test 1 Integration test 2Unit test 3Functional test 1Unit test 4CodePHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  7. 7. Types of tests in MVC frameworksUnit test 1 Unit test 2Integration test 1 Integration test 2Unit test 3Functional test 1Unit test 4Controllers/ViewsModelsThe states and the dependencies in controllers/views makes unit testing completely useless from aserver-side point of view.Not true when considering javascript testing and other front-end behaviour/functionality which canbe done in other waysPHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  8. 8. Enters PHPUnitPHPUnit help you deal with unit andintegration tests. http://www.phpunit.de/Provides everything needed for any type oftest.Produces reports in different formats (also forcode coverage).Yii provides the functionality to integrate andautomate PHPUnit without worrying too muchabout configuration.PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  9. 9. Configuring tests in YiiHave PHPUnit installed and a Yii app ready.Directory structure available:protected/tests/ main directory for all testsunit/ unit tests directoryfixtures/ fixtures directoryphpunit.xml main phpunit config filebootstrap.php Yii related configurationPHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  10. 10. Setup a test DBIn protected/tests/bootstrap.php :$config=dirname(__FILE__)./../config/test.php;In protected/config/test.php :db=>array(connectionString => mysql:host=localhost;dbname=myproject_test,),PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  11. 11. // tests/unit/doodleTest.phpclass DoodleTest extends DBbTestCase{//.../*** Test getImageSrc returns what* has been passed to setImageSrc*/public functiontestGetImageSrcRerturnsWhatHasBeenPassedToSetImageSrc() {$model = new Doodle();$expectedImageSrc = Something;$model->imageSrc = $expectedImgSrc;$this->assertEquals($expectedImgSrc,$model->imageSrc);}//...}// models/Doodle.phpclass Doodle extends CActiveRecord{//...private $_imageSrc = null;public function setImageSrc($data){$this->_imageSrc = $data;}public function getImageSrc() {return $this->_imageSrc;}//...}Write your testsTests are made ofassertions[see full list at phpunit.de]PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  12. 12. //.../*** Data Provider for getImageSrc / setImageSrc** @return array*/public function imgSrcDataProvider() {return array(array(null),array(some random text),array(0),array(-1));}//...}// tests/unit/doodleTest.phpclass DoodleTest extends DBbTestCase{//.../*** Test getImageSrc returns what has been passed tosetImageSrc** @dataProvider imgSrcDataProvider*/public functiontestGetImageSrcRerturnsWhatHasBeenPassedToSetImageSrc($expectedImgSrc) {$model = new Doodle();if ($expectedImgSrc !== null) {$model->imageSrc = $expectedImgSrc;}$this->assertEquals($expectedImgSrc,$model->imageSrc);}//...Testing all cases: DataProvidersPHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  13. 13. Database Interaction and AR classesJust load the project database structure.Fill in the tables that will not change during thetests.Create and save objects as needed...(this is normally not enough)Objects that are loaded, modified and updatedfrom and to the database require the use of Yiifixtures.PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  14. 14. public $fixtures = array(users => User, // <generic_name> => <table_name>);Yii FixturesFlexible and useful way to deal with a mutable set of data.Defined in protected/tests/fixtures/<lowercase-tablename>.phpContains a return statement of an array of arrays.Each first level array is a row. Each row can be keyindexed.Setup at the top of the test Class with:PHP Unit Testing in Yii - 13/06/2013 - Yii London MeetupFor every test in the class the fixtured tables will beemptied and filled in with the data (this could be quiteexpensive).
  15. 15. 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());}Fixtures usesThis is just an example onhow you can use the datafrom the fixture array.You can always load thesame data that has beenloaded into the table and usethat.More examples provided inthe Yii Definitive Guide.PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  16. 16. Other important features● testing exceptions using@expectedException <Exception>● Mocks and Stubs:○ mock dependencies, injecting objects and resolvedependencies○ prepare stubs with methods that returns specificvalues based on certain conditions● a lot more other stuff depending on yourneeds.PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  17. 17. Command line invocationtest everything:$ cd /path/to/project/protected/tests/$ phpunit unitPHPUnit 3.6.11 by Sebastian Bergmann.Configuration read from /path/to/project/protected/tests/phpunit.xml................................................................. 65 / 86 ( 75%).....................Time: 01:02, Memory: 18.00MOK (86 tests, 91 assertions)$PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  18. 18. Command line invocation (2)test a single file:$ phpunit unit/CustomerTest.phpTime: 1 second, Memory: 15.00MbOK (32 tests, 37 assertions)or a single test method using a pattern:$ phpunit --filter testCustomerStartEndDates unit/CustomerTest.phpTime: 1 second, Memory: 15.00MbOK (32 tests, 37 assertions)for more info theres always$ phpunit --helpPHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  19. 19. More information and resourcesSpecific to PHPUnit and Yii Unit TestingPHPUnit manualhttp://phpunit.de/manual/current/en/index.htmlYii Guide on testinghttp://www.yiiframework.com/doc/guide/1.1/en/test.overviewGeneric information on TDDContent Creation Wiki entry on TDD: http://c2.com/cgi/wiki?TestDrivenDevelopmentSoftware Development Maghttp://www.methodsandtools.com/archive/archive.php?id=20PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  20. 20. Thank you!Make a kitten happy and start testing today!PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup

×