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

What's hot

What should a hacker know about WebDav?
What should a hacker know about WebDav?What should a hacker know about WebDav?
What should a hacker know about WebDav?
Mikhail Egorov
 
Intro to exploits in metasploitand payloads in msfvenom
Intro to exploits in metasploitand payloads in msfvenomIntro to exploits in metasploitand payloads in msfvenom
Intro to exploits in metasploitand payloads in msfvenom
Siddharth Krishna Kumar
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Christopher Frohoff
 
Hacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesHacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sites
Mikhail Egorov
 
메이븐 기본 이해
메이븐 기본 이해메이븐 기본 이해
메이븐 기본 이해
중선 곽
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
Jim Yeh
 
Practical SAP pentesting workshop (NullCon Goa)
Practical SAP pentesting workshop (NullCon Goa)Practical SAP pentesting workshop (NullCon Goa)
Practical SAP pentesting workshop (NullCon Goa)
ERPScan
 
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programsAEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
Mikhail Egorov
 
스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해
beom kyun choi
 
Codeception presentation
Codeception presentationCodeception presentation
Codeception presentation
Andrei Burian
 
[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode
Akihiro Suda
 
Multi Tenancy With Python and Django
Multi Tenancy With Python and DjangoMulti Tenancy With Python and Django
Multi Tenancy With Python and Django
scottcrespo
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
Michel Schildmeijer
 
Hunting for security bugs in AEM webapps
Hunting for security bugs in AEM webappsHunting for security bugs in AEM webapps
Hunting for security bugs in AEM webapps
Mikhail Egorov
 
Developing MIPS Exploits to Hack Routers
Developing MIPS Exploits to Hack RoutersDeveloping MIPS Exploits to Hack Routers
Developing MIPS Exploits to Hack Routers
BGA Cyber Security
 
Introduction to Maven
Introduction to MavenIntroduction to Maven
Introduction to Maven
Mindfire Solutions
 
Scaling Yii2 Application
Scaling Yii2 ApplicationScaling Yii2 Application
Scaling Yii2 Application
Petra Barus
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
Soroush Dalili
 
테스터도 알아야 할 웹 개발(테스트 교육 3장 1절 부분발췌)
테스터도 알아야 할 웹 개발(테스트 교육 3장 1절 부분발췌)테스터도 알아야 할 웹 개발(테스트 교육 3장 1절 부분발췌)
테스터도 알아야 할 웹 개발(테스트 교육 3장 1절 부분발췌)
SangIn Choung
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
Antoine Rey
 

What's hot (20)

What should a hacker know about WebDav?
What should a hacker know about WebDav?What should a hacker know about WebDav?
What should a hacker know about WebDav?
 
Intro to exploits in metasploitand payloads in msfvenom
Intro to exploits in metasploitand payloads in msfvenomIntro to exploits in metasploitand payloads in msfvenom
Intro to exploits in metasploitand payloads in msfvenom
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
 
Hacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesHacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sites
 
메이븐 기본 이해
메이븐 기본 이해메이븐 기본 이해
메이븐 기본 이해
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
 
Practical SAP pentesting workshop (NullCon Goa)
Practical SAP pentesting workshop (NullCon Goa)Practical SAP pentesting workshop (NullCon Goa)
Practical SAP pentesting workshop (NullCon Goa)
 
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programsAEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
 
스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해
 
Codeception presentation
Codeception presentationCodeception presentation
Codeception presentation
 
[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode
 
Multi Tenancy With Python and Django
Multi Tenancy With Python and DjangoMulti Tenancy With Python and Django
Multi Tenancy With Python and Django
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
 
Hunting for security bugs in AEM webapps
Hunting for security bugs in AEM webappsHunting for security bugs in AEM webapps
Hunting for security bugs in AEM webapps
 
Developing MIPS Exploits to Hack Routers
Developing MIPS Exploits to Hack RoutersDeveloping MIPS Exploits to Hack Routers
Developing MIPS Exploits to Hack Routers
 
Introduction to Maven
Introduction to MavenIntroduction to Maven
Introduction to Maven
 
Scaling Yii2 Application
Scaling Yii2 ApplicationScaling Yii2 Application
Scaling Yii2 Application
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
 
테스터도 알아야 할 웹 개발(테스트 교육 3장 1절 부분발췌)
테스터도 알아야 할 웹 개발(테스트 교육 3장 1절 부분발췌)테스터도 알아야 할 웹 개발(테스트 교육 3장 1절 부분발췌)
테스터도 알아야 할 웹 개발(테스트 교육 3장 1절 부분발췌)
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 

Viewers also liked

Introduce Yii
Introduce YiiIntroduce Yii
Introduce Yii
zakieh alizadeh
 
Yii Training session-1
Yii Training session-1Yii Training session-1
Yii Training session-1
AkkiCredencys
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
Chandra S Oemarjadi
 
YiiConf 2012 - Alexander Makarov - Yii2, what's new
YiiConf 2012 - Alexander Makarov - Yii2, what's newYiiConf 2012 - Alexander Makarov - Yii2, what's new
YiiConf 2012 - Alexander Makarov - Yii2, what's newAlexander Makarov
 
1ST TECH TALK: "Yii : The MVC framework" by Benedicto B. Balilo Jr.
1ST TECH TALK: "Yii : The MVC framework" by Benedicto B. Balilo Jr.1ST TECH TALK: "Yii : The MVC framework" by Benedicto B. Balilo Jr.
1ST TECH TALK: "Yii : The MVC framework" by Benedicto B. Balilo Jr.Bicol IT.org
 
Yii PHP MVC Framework presentation silicongulf.com
Yii PHP MVC Framework presentation silicongulf.comYii PHP MVC Framework presentation silicongulf.com
Yii PHP MVC Framework presentation silicongulf.com
Christopher Cubos
 
Devconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developedDevconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developed
Alexander Makarov
 
A site in 15 minutes with yii
A site in 15 minutes with yiiA site in 15 minutes with yii
A site in 15 minutes with yii
Andy Kelk
 
Yii framework
Yii frameworkYii framework
Yii framework
Pratik Gondaliya
 
Testing with Codeception
Testing with CodeceptionTesting with Codeception
Testing with Codeception
Jeremy Coates
 
Yii framework
Yii frameworkYii framework
Yii framework
Leena Roja
 
Introduction Yii Framework
Introduction Yii FrameworkIntroduction Yii Framework
Introduction Yii Framework
Tuan Nguyen
 
Yii Framework
Yii FrameworkYii Framework
Yii Framework
Jason Ragsdale
 

Viewers also liked (16)

Introduce Yii
Introduce YiiIntroduce Yii
Introduce Yii
 
Yii Training session-1
Yii Training session-1Yii Training session-1
Yii Training session-1
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
YiiConf 2012 - Alexander Makarov - Yii2, what's new
YiiConf 2012 - Alexander Makarov - Yii2, what's newYiiConf 2012 - Alexander Makarov - Yii2, what's new
YiiConf 2012 - Alexander Makarov - Yii2, what's new
 
1ST TECH TALK: "Yii : The MVC framework" by Benedicto B. Balilo Jr.
1ST TECH TALK: "Yii : The MVC framework" by Benedicto B. Balilo Jr.1ST TECH TALK: "Yii : The MVC framework" by Benedicto B. Balilo Jr.
1ST TECH TALK: "Yii : The MVC framework" by Benedicto B. Balilo Jr.
 
Yii PHP MVC Framework presentation silicongulf.com
Yii PHP MVC Framework presentation silicongulf.comYii PHP MVC Framework presentation silicongulf.com
Yii PHP MVC Framework presentation silicongulf.com
 
Devconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developedDevconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developed
 
Yii workshop
Yii workshopYii workshop
Yii workshop
 
A site in 15 minutes with yii
A site in 15 minutes with yiiA site in 15 minutes with yii
A site in 15 minutes with yii
 
Yii framework
Yii frameworkYii framework
Yii framework
 
yii framework
yii frameworkyii framework
yii framework
 
Testing with Codeception
Testing with CodeceptionTesting with Codeception
Testing with Codeception
 
X-Debug in Php Storm
X-Debug in Php StormX-Debug in Php Storm
X-Debug in Php Storm
 
Yii framework
Yii frameworkYii framework
Yii framework
 
Introduction Yii Framework
Introduction Yii FrameworkIntroduction Yii Framework
Introduction Yii Framework
 
Yii Framework
Yii FrameworkYii Framework
Yii Framework
 

Similar to PHP Unit Testing in Yii

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
pleeps
 
Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit Test
Phuoc Bui
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps
Venkata Ramana
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
Paul Blundell
 
PHPUnit your bug exterminator
PHPUnit your bug exterminatorPHPUnit your bug exterminator
PHPUnit your bug exterminator
rjsmelo
 
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
Andrea Paciolla
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
Peter Arato
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
Peter Gfader
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
Seb Rose
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
PHP Barcelona 2010 - Architecture and testability
PHP Barcelona 2010 - Architecture and testabilityPHP Barcelona 2010 - Architecture and testability
PHP Barcelona 2010 - Architecture and testability
Giorgio Sironi
 
PHPUnit
PHPUnitPHPUnit
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
davejohnson
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
Jim Lynch
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
JWORKS powered by Ordina
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Ukraine
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 

Similar to PHP Unit Testing in Yii (20)

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit Test
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 
PHPUnit your bug exterminator
PHPUnit your bug exterminatorPHPUnit your bug exterminator
PHPUnit your bug exterminator
 
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
PHP Barcelona 2010 - Architecture and testability
PHP Barcelona 2010 - Architecture and testabilityPHP Barcelona 2010 - Architecture and testability
PHP Barcelona 2010 - Architecture and testability
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 

Recently uploaded

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 

Recently uploaded (20)

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 

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