SlideShare a Scribd company logo
PHP Unit Testing
in Yii
How to start with TDD in Yii
by Matteo 'Peach' Pescarin
Twitter: @ilPeach
13/06/2013 - Yii London Meetup
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
Test Driven Development (TDD)
"encourages simple design and inspires
confidence" - Kent Beck
Re-discovered in 2004, is related to the test-
first concept from eXtreme Programming.
Works with any Agile methodology, but can be
applied in any context.
Also useful when dealing with legacy code that
wasn't 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
What is Unit Testing?
It's not about bug finding (there's no way this
can be proved to be true).
It's about designing software components
robustly.
The behaviour of the units is specified through
the 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
Some tips to write Unit Tests
They must be isolated from each other:
● Every behaviour should be covered by one test.
● No unnecessary assertions (TDD: one logical assertion
per test)
● Test one code-unit at a time (this should force you write
non-overlapping code, or use IoC, Inversion of Control)
● Mock external services and states (without abusing)
● Avoid preconditions (although it might be useful
sometimes)
Don't test configuration settings.
Name your tests clearly and consistently.
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
Types of tests
Unit test 1 Unit test 2
Integration test 1 Integration test 2
Unit test 3
Functional test 1
Unit test 4
Code
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
Types of tests in MVC frameworks
Unit test 1 Unit test 2
Integration test 1 Integration test 2
Unit test 3
Functional test 1
Unit test 4
Controllers/Views
Models
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
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
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.
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
Configuring tests in Yii
Have PHPUnit installed and a Yii app ready.
Directory structure available:
protected/tests/ main directory for all tests
unit/ unit tests directory
fixtures/ fixtures directory
phpunit.xml main phpunit config file
bootstrap.php Yii related configuration
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
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',
),
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
// 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
);
}
//...
}
// models/Doodle.php
class Doodle extends CActiveRecord
{
//...
private $_imageSrc = null;
public function setImageSrc($data)
{
$this->_imageSrc = $data;
}
public function getImageSrc() {
return $this->_imageSrc;
}
//...
}
Write your tests
Tests are made of
assertions
[see full list at phpunit.de]
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
//...
/**
* 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.php
class DoodleTest extends DBbTestCase
{
//...
/**
* Test getImageSrc returns what has been passed to
setImageSrc
*
* @dataProvider imgSrcDataProvider
*/
public function
testGetImageSrcRerturnsWhatHasBeenPassedToSetImageSrc(
$expectedImgSrc
) {
$model = new Doodle();
if ($expectedImgSrc !== null) {
$model->imageSrc = $expectedImgSrc;
}
$this->assertEquals(
$expectedImgSrc,
$model->imageSrc
);
}
//...
Testing all cases: DataProviders
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
Database Interaction and AR classes
Just load the project database structure.
Fill in the tables that will not change during the
tests.
Create and save objects as needed...
(this is normally not enough)
Objects that are loaded, modified and updated
from and to the database require the use of Yii
fixtures.
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
public $fixtures = array(
'users' => 'User', // <generic_name> => <table_name>
);
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:
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
For every test in the class the fixtured tables will be
emptied and filled in with the data (this could be quite
expensive).
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 uses
This is just an example on
how you can use the data
from the fixture array.
You can always load the
same data that has been
loaded into the table and use
that.
More examples provided in
the Yii Definitive Guide.
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
Other important features
● testing exceptions using
@expectedException <Exception>
● Mocks and Stubs:
○ mock dependencies, injecting objects and resolve
dependencies
○ prepare stubs with methods that returns specific
values based on certain conditions
● a lot more other stuff depending on your
needs.
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
Command line invocation
test everything:
$ cd /path/to/project/protected/tests/
$ phpunit unit
PHPUnit 3.6.11 by Sebastian Bergmann.
Configuration read from /path/to/project/protected/tests/phpunit.xml
................................................................. 65 / 86 ( 75%)
.....................
Time: 01:02, Memory: 18.00M
OK (86 tests, 91 assertions)
$
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
Command line invocation (2)
test a single file:
$ phpunit unit/CustomerTest.php
Time: 1 second, Memory: 15.00Mb
OK (32 tests, 37 assertions)
or a single test method using a pattern:
$ phpunit --filter testCustomerStartEndDates unit/CustomerTest.php
Time: 1 second, Memory: 15.00Mb
OK (32 tests, 37 assertions)
for more info there's always
$ phpunit --help
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
More information and resources
Specific to PHPUnit and Yii Unit Testing
PHPUnit manual
http://phpunit.de/manual/current/en/index.html
Yii Guide on testing
http://www.yiiframework.com/doc/guide/1.1/en/test.overview
Generic information on TDD
Content Creation Wiki entry on TDD: http://c2.com/cgi/wiki?
TestDrivenDevelopment
Software Development Mag
http://www.methodsandtools.com/archive/archive.php?id=20
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
Thank you!
Make a kitten happy and start testing today!
PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup

More Related Content

PPT
PDF
Test Automation Using Python | Edureka
PDF
Robot Framework :: Demo login application
PPTX
Singleton Design Pattern - Creation Pattern
PPTX
Python in Test automation
PPTX
AEM Rich Text Editor (RTE) Deep Dive
PPTX
Pytest KT.pptx
Test Automation Using Python | Edureka
Robot Framework :: Demo login application
Singleton Design Pattern - Creation Pattern
Python in Test automation
AEM Rich Text Editor (RTE) Deep Dive
Pytest KT.pptx

What's hot (20)

PDF
Ruin your life using robot framework
PPTX
Automation - web testing with selenium
PPTX
Security Code Review 101
PPTX
Python/Flask Presentation
PPT
Tomcat server
PPTX
Mastering the Sling Rewriter
PPTX
Test Design and Automation for REST API
PPTX
Pentesting ReST API
PPTX
COM Hijacking Techniques - Derbycon 2019
PDF
PPTX
Unit Testing in Java
PDF
Python's magic methods
PPTX
Introduction to OOP(in java) BY Govind Singh
PDF
Build and Distributing SDK Add-Ons
PPTX
Async/Await
PDF
Java 8 Lambda Expressions & Streams
PPTX
Selenium WebDriver
PPTX
Exceptions in Java
PPT
Automated Web Testing Using Selenium
PPTX
Robot framework Gowthami Goli
Ruin your life using robot framework
Automation - web testing with selenium
Security Code Review 101
Python/Flask Presentation
Tomcat server
Mastering the Sling Rewriter
Test Design and Automation for REST API
Pentesting ReST API
COM Hijacking Techniques - Derbycon 2019
Unit Testing in Java
Python's magic methods
Introduction to OOP(in java) BY Govind Singh
Build and Distributing SDK Add-Ons
Async/Await
Java 8 Lambda Expressions & Streams
Selenium WebDriver
Exceptions in Java
Automated Web Testing Using Selenium
Robot framework Gowthami Goli
Ad

Viewers also liked (17)

PDF
Codeception introduction and use in Yii
PDF
Introduce Yii
PPTX
Yii Training session-1
PPTX
Yii Introduction
PDF
YiiConf 2012 - Alexander Makarov - Yii2, what's new
PPT
1ST TECH TALK: "Yii : The MVC framework" by Benedicto B. Balilo Jr.
PDF
Yii PHP MVC Framework presentation silicongulf.com
PDF
Devconf 2011 - PHP - How Yii framework is developed
PPT
Yii workshop
PPTX
A site in 15 minutes with yii
PPT
Yii framework
PPTX
yii framework
PDF
Testing with Codeception
PDF
X-Debug in Php Storm
PPTX
Yii framework
PDF
Introduction Yii Framework
KEY
Yii Framework
Codeception introduction and use in Yii
Introduce Yii
Yii Training session-1
Yii Introduction
YiiConf 2012 - Alexander Makarov - Yii2, what's new
1ST TECH TALK: "Yii : The MVC framework" by Benedicto B. Balilo Jr.
Yii PHP MVC Framework presentation silicongulf.com
Devconf 2011 - PHP - How Yii framework is developed
Yii workshop
A site in 15 minutes with yii
Yii framework
yii framework
Testing with Codeception
X-Debug in Php Storm
Yii framework
Introduction Yii Framework
Yii Framework
Ad

Similar to PHP Unit Testing in Yii (20)

KEY
Developer testing 101: Become a Testing Fanatic
PDF
Leveling Up With Unit Testing - LonghornPHP 2022
PPTX
Unit testing
PPTX
PHPUnit: from zero to hero
PPTX
Getting started-php unit
PPT
Automated Unit Testing
KEY
Php Unit With Zend Framework Zendcon09
PDF
Fighting Fear-Driven-Development With PHPUnit
PPTX
Test in action week 2
PDF
PHPunit and you
PDF
Introduction to Unit Testing with PHPUnit
PPT
Unit testing
PDF
Unit testing in PHP
PPT
Unit Testing using PHPUnit
PPTX
Unit Testng with PHP Unit - A Step by Step Training
KEY
PHPUnit testing to Zend_Test
PPT
Unit testing php-unit - phing - selenium_v2
PDF
Leveling Up With Unit Testing - php[tek] 2023
PDF
Unit Testing from Setup to Deployment
ZIP
Test
Developer testing 101: Become a Testing Fanatic
Leveling Up With Unit Testing - LonghornPHP 2022
Unit testing
PHPUnit: from zero to hero
Getting started-php unit
Automated Unit Testing
Php Unit With Zend Framework Zendcon09
Fighting Fear-Driven-Development With PHPUnit
Test in action week 2
PHPunit and you
Introduction to Unit Testing with PHPUnit
Unit testing
Unit testing in PHP
Unit Testing using PHPUnit
Unit Testng with PHP Unit - A Step by Step Training
PHPUnit testing to Zend_Test
Unit testing php-unit - phing - selenium_v2
Leveling Up With Unit Testing - php[tek] 2023
Unit Testing from Setup to Deployment
Test

Recently uploaded (20)

PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
Teaching material agriculture food technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Spectroscopy.pptx food analysis technology
PPTX
MYSQL Presentation for SQL database connectivity
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Unlocking AI with Model Context Protocol (MCP)
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Chapter 3 Spatial Domain Image Processing.pdf
Teaching material agriculture food technology
Building Integrated photovoltaic BIPV_UPV.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Programs and apps: productivity, graphics, security and other tools
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Encapsulation_ Review paper, used for researhc scholars
Understanding_Digital_Forensics_Presentation.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Per capita expenditure prediction using model stacking based on satellite ima...
Digital-Transformation-Roadmap-for-Companies.pptx
Spectroscopy.pptx food analysis technology
MYSQL Presentation for SQL database connectivity
The Rise and Fall of 3GPP – Time for a Sabbatical?

PHP Unit Testing in Yii

  • 1. PHP Unit Testing in Yii How to start with TDD in Yii by Matteo 'Peach' Pescarin Twitter: @ilPeach 13/06/2013 - Yii London Meetup
  • 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. Test Driven Development (TDD) "encourages simple design and inspires confidence" - Kent Beck Re-discovered in 2004, is related to the test- first concept from eXtreme Programming. Works with any Agile methodology, but can be applied in any context. Also useful when dealing with legacy code that wasn't 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. What is Unit Testing? It's not about bug finding (there's no way this can be proved to be true). It's about designing software components robustly. The behaviour of the units is specified through the 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. Some tips to write Unit Tests They must be isolated from each other: ● Every behaviour should be covered by one test. ● No unnecessary assertions (TDD: one logical assertion per test) ● Test one code-unit at a time (this should force you write non-overlapping code, or use IoC, Inversion of Control) ● Mock external services and states (without abusing) ● Avoid preconditions (although it might be useful sometimes) Don't test configuration settings. Name your tests clearly and consistently. PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 6. Types of tests Unit test 1 Unit test 2 Integration test 1 Integration test 2 Unit test 3 Functional test 1 Unit test 4 Code PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 7. Types of tests in MVC frameworks Unit test 1 Unit test 2 Integration test 1 Integration test 2 Unit test 3 Functional test 1 Unit test 4 Controllers/Views Models 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 PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 8. 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. PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 9. Configuring tests in Yii Have PHPUnit installed and a Yii app ready. Directory structure available: protected/tests/ main directory for all tests unit/ unit tests directory fixtures/ fixtures directory phpunit.xml main phpunit config file bootstrap.php Yii related configuration PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 10. 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', ), PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 11. // 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 ); } //... } // models/Doodle.php class Doodle extends CActiveRecord { //... private $_imageSrc = null; public function setImageSrc($data) { $this->_imageSrc = $data; } public function getImageSrc() { return $this->_imageSrc; } //... } Write your tests Tests are made of assertions [see full list at phpunit.de] PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 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.php class DoodleTest extends DBbTestCase { //... /** * Test getImageSrc returns what has been passed to setImageSrc * * @dataProvider imgSrcDataProvider */ public function testGetImageSrcRerturnsWhatHasBeenPassedToSetImageSrc( $expectedImgSrc ) { $model = new Doodle(); if ($expectedImgSrc !== null) { $model->imageSrc = $expectedImgSrc; } $this->assertEquals( $expectedImgSrc, $model->imageSrc ); } //... Testing all cases: DataProviders PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 13. Database Interaction and AR classes Just load the project database structure. Fill in the tables that will not change during the tests. Create and save objects as needed... (this is normally not enough) Objects that are loaded, modified and updated from and to the database require the use of Yii fixtures. PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 14. public $fixtures = array( 'users' => 'User', // <generic_name> => <table_name> ); 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: PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup For every test in the class the fixtured tables will be emptied and filled in with the data (this could be quite expensive).
  • 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 uses This is just an example on how you can use the data from the fixture array. You can always load the same data that has been loaded into the table and use that. More examples provided in the Yii Definitive Guide. PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 16. Other important features ● testing exceptions using @expectedException <Exception> ● Mocks and Stubs: ○ mock dependencies, injecting objects and resolve dependencies ○ prepare stubs with methods that returns specific values based on certain conditions ● a lot more other stuff depending on your needs. PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 17. Command line invocation test everything: $ cd /path/to/project/protected/tests/ $ phpunit unit PHPUnit 3.6.11 by Sebastian Bergmann. Configuration read from /path/to/project/protected/tests/phpunit.xml ................................................................. 65 / 86 ( 75%) ..................... Time: 01:02, Memory: 18.00M OK (86 tests, 91 assertions) $ PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 18. Command line invocation (2) test a single file: $ phpunit unit/CustomerTest.php Time: 1 second, Memory: 15.00Mb OK (32 tests, 37 assertions) or a single test method using a pattern: $ phpunit --filter testCustomerStartEndDates unit/CustomerTest.php Time: 1 second, Memory: 15.00Mb OK (32 tests, 37 assertions) for more info there's always $ phpunit --help PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 19. More information and resources Specific to PHPUnit and Yii Unit Testing PHPUnit manual http://phpunit.de/manual/current/en/index.html Yii Guide on testing http://www.yiiframework.com/doc/guide/1.1/en/test.overview Generic information on TDD Content Creation Wiki entry on TDD: http://c2.com/cgi/wiki? TestDrivenDevelopment Software Development Mag http://www.methodsandtools.com/archive/archive.php?id=20 PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup
  • 20. Thank you! Make a kitten happy and start testing today! PHP Unit Testing in Yii - 13/06/2013 - Yii London Meetup