SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Introduction to PHP
Testing
Ran Mizrahi (@ranm8)
Sunday, October 6, 13
What is Wix?
Enables Everyone to create amazing websites
Need Primary solution
Create a document
Create a presentation
Create a blog
Create a web presence
Sunday, October 6, 13
• Biggest website building platform in the world.
• Everyone - No technical knowledge needed.
• Amazing websites - allow self expression and flexibility.
What is Wix?
Wix in Numbers
38,750,000+ Users 45,000+ Join Wix/Day
15,000+ Apps Installations/Day
Sunday, October 6, 13
Wix App Market
• Enables to develop responsive Wix web apps and sell
apps to Wix’s users.
• Hundreds of apps, each gives our users new amazing
functionality.
• Wix App is actually a web app (HTML app) embedded in
to a Wix site.
Sunday, October 6, 13
Why Do Software Projects Fail?!
• Deliver late or over budget.
• Deliver the wrong thing.
• Unstable in production.
Production Maintenance
• Expensive maintenance.
• Long adjustment to market
needs.
• Long development cycles.
Sunday, October 6, 13
Why Do Software Projects Fail?!
Sunday, October 6, 13
Untestable code... (Common PHP example)
function user($username, $firstName, $lastName, $mail) {
if (!$firstName || !$lastName) {
throw new Exception('First or last name are not valid');
} else if(!is_string($mail) && !filter_var($mail, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Mail is not valid');
} else if(!$username) {
throw new Exception('Username is not valid');
}
$userServer = new UserServer();
try {
$res = $userServer->exec(array(
'fullName' => $firstName . ' ' . $lastName,
'username' => $username,
'mail' => $mail
));
if ($res->code !== 200) {
$message = 'Failed saving user to server';
}
$message = 'Success!';
} catch(Exception $e) {
$message = 'Failed accessing user system';
}
echo $message;
}
Sunday, October 6, 13
Why Test Your Code???
The problems with untestable code:
• Tightly coupled.
• No separation of concerns.
• Not readable.
• Not predictable.
• Global states.
• Long methods.
• Large classes.
Sunday, October 6, 13
Why Test Your Code???
The problems with untestable code:
• Tightly coupled.
• No separation of concerns.
• Not readable.
• Not predictable.
• Global states.
• Long methods.
• Large classes.
>
• Hard to maintain.
• High learning curve.
• Stability issues.
• You can never expect
problems before they
occur
Sunday, October 6, 13
Test-Driven Development To The Recuse!
Methodology for using automated unit
tests to drive software design, quality
and stability.
Sunday, October 6, 13
Test-Driven Development To The Recuse!
How it’s done :
• First the developer writes
a failing test case that
defines a desired
functionality to the
software.
• Makes the code pass
those tests.
• Refactor the code to meet
standards.
Sunday, October 6, 13
Seems Great But How Much Longer Does TDD Takes???
My experience:
• Initial progress will be slower.
• Greater consistency.
• Long tern cost is drastically
lower
• After getting used to it, you
can write TDD faster (-:
Studies:
• Takes 15-30% longer.
• 45-80% less bugs.
• Fixing bugs later on is
dramatically faster.
Sunday, October 6, 13
The Three Rules of TDD
Rule #1
Your code should always fail before you implement the code
Rule #2
Implement the simplest code possible to pass your tests.
Rule #3
Refactor, refactor and refractor - There is no shame in refactoring.
Sunday, October 6, 13
BDD (Behavior-Driven Development)
Test-Driven Development
Sunday, October 6, 13
BDD (Behavior-Driven Development)
Test-Driven Development
What exactly are we testing?!
Sunday, October 6, 13
BDD (Behavior-Driven Development)
• Originally started in 2003 by Dan North, author of JBehave, the
first BDD tool.
• Based on the TDD methodology.
• Aims to provide tools for both developers and business (e.g.
product manager, etc.) to share development process together.
• The steps of BDD :
• Developers and business personas write specification together.
• Developer writes tests based on specs and make them fail.
• Write code to pass those tests.
• Refactor, refactor, refactor...
Sunday, October 6, 13
BDD (Behavior-Driven Development)
Feature: ls
In order to see the directory structure
As a UNIX user
I need to be able to list the current directory's contents
Scenario: List 2 files in a directory
Given I am in a directory "test"
And I have a file named "foo"
And I have a file named "bar"
When I run "ls"
Then I should get:
"""
bar
foo
"""
* Behat example
Sunday, October 6, 13
Main Test Types
• Unit Testing
• Integration Testing
• Functional Testing
Sunday, October 6, 13
Challenges Testing PHP
• You cannot mock global functions in PHP since they are
immutable.
• Procedural code is hard to mock and be tested.
Sunday, October 6, 13
TDD using PHPUnit
PHPUnit is a popular PHP unit testing framework designed for
making unit testing easy in PHP.
PHPUnit
Main features:
• Supports both TDD style assertions.
• Support multiple output formats like jUnit, JSON, TAP.
• Proper exit status for CI support (using jUnit for test results and
clover for code coverage report).
• Supports multiple code coverage report formats like HTML,
JSON, PHP serialized and clover.
• Built-in assertions and matchers.
Sunday, October 6, 13
TDD using PHPUnit
Installing PHPUnit
$ pear config-set auto_discover 1
$ pear install pear.phpunit.de/PHPUnit
Install mocha globally using pear:
$ composer global require ‘phpunit/phpunit=3.8.*’
Install mocha globally using composer:
$ wget https://phar.phpunit.de/phpunit.phar
$ chmod +x phpunit.phar
$ mv phpunit.phar /usr/local/bin/phpunit
Download the PHP archive:
Sunday, October 6, 13
TDD using PHPUnit
Basic test:
Run it..
$ phpunit UserTest.php
PHPUnit 3.7.22 by Sebastian Bergmann.
...
Time: 0 seconds, Memory: 2.50Mb
OK (1 test, 1 assertion)
class UserSpec extends PHPUnit_Framework_TestCase
{
protected $invalidMail = 'invalid-mail';
public function testThatFilterVarReturnsFalseWhenInvalid()
{
$this->assertFalse(filter_var($this->invalidMail, FILTER_VALIDATE_EMAIL));
}
}
Sunday, October 6, 13
Back to our code
Sunday, October 6, 13
First, Let’s Write The Tests!
function user($username, $firstName, $lastName, $mail) {
if (!$firstName || !$lastName) {
throw new Exception('First or last name are not valid');
} else if(!is_string($mail) && !filter_var($mail, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Mail is not valid');
} else if(!$username) {
throw new Exception('Username is not valid');
}
$userServer = new UserServer();
try {
$res = $userServer->exec(array(
'fullName' => $firstName . ' ' . $lastName,
'username' => $username,
'mail' => $mail
));
if ($res->code !== 200) {
$message = 'Failed saving user to server';
}
$message = 'Success!';
} catch(Exception $e) {
$message = 'Failed accessing user system';
}
echo $message;
}
Sunday, October 6, 13
First, Let’s Write The Tests!
What to test in our case:
• Validations.
• Full name getter.
• Post user save actions.
What not to test :
• UserServer object (-: we should isolate our code and test it only.
Sunday, October 6, 13
First, Let’s Write The Tests!
class UserSpec extends PHPUnit_Framework_TestCase
{
protected $user;
protected $userServerMock;
protected $goodResponse;
public function setUp()
{
$this->goodResponse = new stdClass();
$this->goodResponse->code = 200;
$this->userServerMock = $this->getMock('UserServer', array('exec'));
$this->user = new User('anakin', 'Anakin', 'Skywalker', 'anakin@wix.com', $this-
>userServerMock);
}
/**
* @expectedException Exception
*/
public function testThatInvalidMailThrows()
{
$this->user->setMail('invalid-mail');
}
public function testThatValidMailWorks()
{
$validMail = 'me@mail.com';
$this->user->setMail($validMail);
$this->assertEquals($validMail, $this->user->getMail());
}
Sunday, October 6, 13
First, Let’s Write The Tests!
public function testThatUserServerExecIsCalledWhenSavingAUser()
{
$this->userServerMock->expects($this->once())
->method('exec')
->will($this->returnValue($this->goodResponse));
$this->user->save();
}
public function testThatFullNameIsConcatinatedCorrcetly()
{
$this->userServerMock->expects($this->once())
->method('exec')
->with($this->callback(function($data) {
return $data['fullName'] === 'Anakin Skywalker';
}))
->will($this->returnValue($this->goodResponse));
$this->user->save();
}
}
Sunday, October 6, 13
Run those tests
Sunday, October 6, 13
Now, Let’s Write The Code
class User
{
protected $username;
protected $firstName;
protected $lastName;
protected $mail;
protected $userServer;
public function __construct($username, $firstName, $lastName, $mail, $userServer)
{
$this->username = $username;
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->setMail($mail);
$this->userServer = $userServer;
}
public function setMail($mail)
{
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Mail is not valid');
}
$this->mail = $mail;
return $this;
}
Sunday, October 6, 13
Now, Let’s Write The Code
public function getMail() {
return $this->mail;
}
protected function getFullName()
{
return $this->firstName . ' ' . $this->lastName;
}
public function getUsername()
{
return $this->username;
}
public function save() {
$response = $this->userServer->exec(array(
'fullName' => $this->getFullName(),
'mail' => $this->getMail(),
'username' => $this->getUsername()
));
if (!$this->isSuccessful($response->code)) {
return 'Failed saving to user server';
}
return 'Success!';
}
protected function isSuccessful($code)
{
return $code >= 200 && $code < 300;
}
}
Sunday, October 6, 13
Run those tests,
again!
Sunday, October 6, 13
Running The Tests
PHPUnit tests can run and provide different types of results:
• CLI - as demonstrated before using the “phpunit” command.
• CI (e.g. jUnit) - (e.g. $ phpunit --log-junit=[file]).
• HTML||clover code coverage (e.g. $ phpunit --coverage-html=[dir]).
• Many other formats (JSON, TAP, Serialized PHP and more).
Sunday, October 6, 13
Benefits of Testing Your Code
• Short feedback/testing cycle.
• High code coverage of tests that can be at run any time to
provide feedback that the software is functioning.
• Provides detailed spec/docs of the application.
• Less time spent on debugging and refactoring.
• Know what breaks early on.
• Enforces code quality (decoupled) and simplicity.
• Help you focus on writing one job code units.
Sunday, October 6, 13
Questions?
Thank you!
Sunday, October 6, 13

Weitere ähnliche Inhalte

Was ist angesagt?

Ruxmon feb 2013 what happened to rails
Ruxmon feb 2013   what happened to railsRuxmon feb 2013   what happened to rails
Ruxmon feb 2013 what happened to railssnyff
 
DevOOPS: Attacks and Defenses for DevOps Toolchains
DevOOPS: Attacks and Defenses for DevOps ToolchainsDevOOPS: Attacks and Defenses for DevOps Toolchains
DevOOPS: Attacks and Defenses for DevOps ToolchainsChris Gates
 
WordPress Plugin Unit Tests (FR - WordCamp Paris 2015)
WordPress Plugin Unit Tests (FR - WordCamp Paris 2015)WordPress Plugin Unit Tests (FR - WordCamp Paris 2015)
WordPress Plugin Unit Tests (FR - WordCamp Paris 2015)Ozh
 
Ln monitoring repositories
Ln monitoring repositoriesLn monitoring repositories
Ln monitoring repositoriessnyff
 
Pwning mobile apps without root or jailbreak
Pwning mobile apps without root or jailbreakPwning mobile apps without root or jailbreak
Pwning mobile apps without root or jailbreakAbraham Aranguren
 
Ruxmon cve 2012-2661
Ruxmon cve 2012-2661Ruxmon cve 2012-2661
Ruxmon cve 2012-2661snyff
 
Adventures in Asymmetric Warfare
Adventures in Asymmetric WarfareAdventures in Asymmetric Warfare
Adventures in Asymmetric WarfareWill Schroeder
 
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat Pôle Systematic Paris-Region
 
PuppetConf 2016: Puppet 4.x: The Low WAT-tage Edition – Nick Fagerlund, Puppet
PuppetConf 2016: Puppet 4.x: The Low WAT-tage Edition – Nick Fagerlund, PuppetPuppetConf 2016: Puppet 4.x: The Low WAT-tage Edition – Nick Fagerlund, Puppet
PuppetConf 2016: Puppet 4.x: The Low WAT-tage Edition – Nick Fagerlund, PuppetPuppet
 
Pwning with powershell
Pwning with powershellPwning with powershell
Pwning with powershelljaredhaight
 
Catch Me If You Can: PowerShell Red vs Blue
Catch Me If You Can: PowerShell Red vs BlueCatch Me If You Can: PowerShell Red vs Blue
Catch Me If You Can: PowerShell Red vs BlueWill Schroeder
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoojeresig
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration TestersNikhil Mittal
 
Dirty Little Secrets They Didn't Teach You In Pentest Class v2
Dirty Little Secrets They Didn't Teach You In Pentest Class v2Dirty Little Secrets They Didn't Teach You In Pentest Class v2
Dirty Little Secrets They Didn't Teach You In Pentest Class v2Rob Fuller
 
BH Arsenal '14 TurboTalk: The Veil-framework
BH Arsenal '14 TurboTalk: The Veil-frameworkBH Arsenal '14 TurboTalk: The Veil-framework
BH Arsenal '14 TurboTalk: The Veil-frameworkVeilFramework
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 
Augeas, swiss knife resources for your puppet tree
Augeas, swiss knife resources for your puppet treeAugeas, swiss knife resources for your puppet tree
Augeas, swiss knife resources for your puppet treeJulien Pivotto
 

Was ist angesagt? (20)

Ruxmon feb 2013 what happened to rails
Ruxmon feb 2013   what happened to railsRuxmon feb 2013   what happened to rails
Ruxmon feb 2013 what happened to rails
 
DevOOPS: Attacks and Defenses for DevOps Toolchains
DevOOPS: Attacks and Defenses for DevOps ToolchainsDevOOPS: Attacks and Defenses for DevOps Toolchains
DevOOPS: Attacks and Defenses for DevOps Toolchains
 
WordPress Plugin Unit Tests (FR - WordCamp Paris 2015)
WordPress Plugin Unit Tests (FR - WordCamp Paris 2015)WordPress Plugin Unit Tests (FR - WordCamp Paris 2015)
WordPress Plugin Unit Tests (FR - WordCamp Paris 2015)
 
Ln monitoring repositories
Ln monitoring repositoriesLn monitoring repositories
Ln monitoring repositories
 
Pwning mobile apps without root or jailbreak
Pwning mobile apps without root or jailbreakPwning mobile apps without root or jailbreak
Pwning mobile apps without root or jailbreak
 
Ruxmon cve 2012-2661
Ruxmon cve 2012-2661Ruxmon cve 2012-2661
Ruxmon cve 2012-2661
 
Adventures in Asymmetric Warfare
Adventures in Asymmetric WarfareAdventures in Asymmetric Warfare
Adventures in Asymmetric Warfare
 
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
 
Testing with PostgreSQL
Testing with PostgreSQLTesting with PostgreSQL
Testing with PostgreSQL
 
PuppetConf 2016: Puppet 4.x: The Low WAT-tage Edition – Nick Fagerlund, Puppet
PuppetConf 2016: Puppet 4.x: The Low WAT-tage Edition – Nick Fagerlund, PuppetPuppetConf 2016: Puppet 4.x: The Low WAT-tage Edition – Nick Fagerlund, Puppet
PuppetConf 2016: Puppet 4.x: The Low WAT-tage Edition – Nick Fagerlund, Puppet
 
Pwning with powershell
Pwning with powershellPwning with powershell
Pwning with powershell
 
Catch Me If You Can: PowerShell Red vs Blue
Catch Me If You Can: PowerShell Red vs BlueCatch Me If You Can: PowerShell Red vs Blue
Catch Me If You Can: PowerShell Red vs Blue
 
ABCs of docker
ABCs of dockerABCs of docker
ABCs of docker
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration Testers
 
Dirty Little Secrets They Didn't Teach You In Pentest Class v2
Dirty Little Secrets They Didn't Teach You In Pentest Class v2Dirty Little Secrets They Didn't Teach You In Pentest Class v2
Dirty Little Secrets They Didn't Teach You In Pentest Class v2
 
BH Arsenal '14 TurboTalk: The Veil-framework
BH Arsenal '14 TurboTalk: The Veil-frameworkBH Arsenal '14 TurboTalk: The Veil-framework
BH Arsenal '14 TurboTalk: The Veil-framework
 
Dust.js
Dust.jsDust.js
Dust.js
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Augeas, swiss knife resources for your puppet tree
Augeas, swiss knife resources for your puppet treeAugeas, swiss knife resources for your puppet tree
Augeas, swiss knife resources for your puppet tree
 

Andere mochten auch (20)

Esnips new version
Esnips new versionEsnips new version
Esnips new version
 
Diadrastikoi pe60 70
Diadrastikoi pe60 70Diadrastikoi pe60 70
Diadrastikoi pe60 70
 
Technologies that will transform small business
Technologies that will transform small businessTechnologies that will transform small business
Technologies that will transform small business
 
Opening up the web
Opening up the webOpening up the web
Opening up the web
 
Angles in Life Project
Angles in Life ProjectAngles in Life Project
Angles in Life Project
 
Arts1510 fall 2012 - requirements
Arts1510   fall 2012 - requirementsArts1510   fall 2012 - requirements
Arts1510 fall 2012 - requirements
 
1124
11241124
1124
 
Gita ch 3
Gita ch 3Gita ch 3
Gita ch 3
 
1119
11191119
1119
 
Gmailaccount
GmailaccountGmailaccount
Gmailaccount
 
4. prosegizontas tin ekpadeutiki omada
4. prosegizontas tin ekpadeutiki omada4. prosegizontas tin ekpadeutiki omada
4. prosegizontas tin ekpadeutiki omada
 
0211
02110211
0211
 
παρουσίαση Blog pathfinder
παρουσίαση Blog pathfinderπαρουσίαση Blog pathfinder
παρουσίαση Blog pathfinder
 
Om at være MOOC'er -at finde og skabe sine egne læringsstier
Om at være MOOC'er -at finde og skabe sine egne læringsstierOm at være MOOC'er -at finde og skabe sine egne læringsstier
Om at være MOOC'er -at finde og skabe sine egne læringsstier
 
Flvconverter
FlvconverterFlvconverter
Flvconverter
 
Brazilian protests – June 2013
Brazilian protests – June 2013Brazilian protests – June 2013
Brazilian protests – June 2013
 
16 golden rules to increase sales
16 golden rules to increase sales16 golden rules to increase sales
16 golden rules to increase sales
 
Le apparizioni di Maria a Lourdes
Le apparizioni di Maria a LourdesLe apparizioni di Maria a Lourdes
Le apparizioni di Maria a Lourdes
 
Introduction to Elgg
Introduction to ElggIntroduction to Elgg
Introduction to Elgg
 
Realplayeruse
RealplayeruseRealplayeruse
Realplayeruse
 

Ähnlich wie PHP Unit Testing Introduction

Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript TestingRan Mizrahi
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIwajrcs
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to TestZsolt Fabok
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Fix me if you can - DrupalCon prague
Fix me if you can - DrupalCon pragueFix me if you can - DrupalCon prague
Fix me if you can - DrupalCon praguehernanibf
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMSJustinHolt20
 
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitIntroduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitRan Mizrahi
 
Practical Chaos Engineering
Practical Chaos EngineeringPractical Chaos Engineering
Practical Chaos EngineeringSIGHUP
 
Creating a Responsive Website From Scratch
Creating a Responsive Website From ScratchCreating a Responsive Website From Scratch
Creating a Responsive Website From ScratchCorky Brown
 
JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook
JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A CookbookJavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook
JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A CookbookJorge Hidalgo
 
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...QAFest
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchMats Bryntse
 
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdf
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdfAstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdf
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdfFarHanWasif1
 
Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Scott Keck-Warren
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Advanced Java Testing @ POSS 2019
Advanced Java Testing @ POSS 2019Advanced Java Testing @ POSS 2019
Advanced Java Testing @ POSS 2019Vincent Massol
 

Ähnlich wie PHP Unit Testing Introduction (20)

Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript Testing
 
Continuous feature-development
Continuous feature-developmentContinuous feature-development
Continuous feature-development
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
 
Case study
Case studyCase study
Case study
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
Fix me if you can - DrupalCon prague
Fix me if you can - DrupalCon pragueFix me if you can - DrupalCon prague
Fix me if you can - DrupalCon prague
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMS
 
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitIntroduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim Summit
 
Practical Chaos Engineering
Practical Chaos EngineeringPractical Chaos Engineering
Practical Chaos Engineering
 
Creating a Responsive Website From Scratch
Creating a Responsive Website From ScratchCreating a Responsive Website From Scratch
Creating a Responsive Website From Scratch
 
JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook
JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A CookbookJavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook
JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook
 
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdf
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdfAstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdf
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdf
 
Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Advanced Java Testing @ POSS 2019
Advanced Java Testing @ POSS 2019Advanced Java Testing @ POSS 2019
Advanced Java Testing @ POSS 2019
 

Mehr von Ran Mizrahi

Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiRan Mizrahi
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJSRan Mizrahi
 
Wix Application Framework
Wix Application FrameworkWix Application Framework
Wix Application FrameworkRan Mizrahi
 
Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8Ran Mizrahi
 

Mehr von Ran Mizrahi (7)

Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
 
Wix Application Framework
Wix Application FrameworkWix Application Framework
Wix Application Framework
 
Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8
 

Kürzlich hochgeladen

Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

PHP Unit Testing Introduction

  • 1. Introduction to PHP Testing Ran Mizrahi (@ranm8) Sunday, October 6, 13
  • 2. What is Wix? Enables Everyone to create amazing websites Need Primary solution Create a document Create a presentation Create a blog Create a web presence Sunday, October 6, 13
  • 3. • Biggest website building platform in the world. • Everyone - No technical knowledge needed. • Amazing websites - allow self expression and flexibility. What is Wix? Wix in Numbers 38,750,000+ Users 45,000+ Join Wix/Day 15,000+ Apps Installations/Day Sunday, October 6, 13
  • 4. Wix App Market • Enables to develop responsive Wix web apps and sell apps to Wix’s users. • Hundreds of apps, each gives our users new amazing functionality. • Wix App is actually a web app (HTML app) embedded in to a Wix site. Sunday, October 6, 13
  • 5. Why Do Software Projects Fail?! • Deliver late or over budget. • Deliver the wrong thing. • Unstable in production. Production Maintenance • Expensive maintenance. • Long adjustment to market needs. • Long development cycles. Sunday, October 6, 13
  • 6. Why Do Software Projects Fail?! Sunday, October 6, 13
  • 7. Untestable code... (Common PHP example) function user($username, $firstName, $lastName, $mail) { if (!$firstName || !$lastName) { throw new Exception('First or last name are not valid'); } else if(!is_string($mail) && !filter_var($mail, FILTER_VALIDATE_EMAIL)) { throw new Exception('Mail is not valid'); } else if(!$username) { throw new Exception('Username is not valid'); } $userServer = new UserServer(); try { $res = $userServer->exec(array( 'fullName' => $firstName . ' ' . $lastName, 'username' => $username, 'mail' => $mail )); if ($res->code !== 200) { $message = 'Failed saving user to server'; } $message = 'Success!'; } catch(Exception $e) { $message = 'Failed accessing user system'; } echo $message; } Sunday, October 6, 13
  • 8. Why Test Your Code??? The problems with untestable code: • Tightly coupled. • No separation of concerns. • Not readable. • Not predictable. • Global states. • Long methods. • Large classes. Sunday, October 6, 13
  • 9. Why Test Your Code??? The problems with untestable code: • Tightly coupled. • No separation of concerns. • Not readable. • Not predictable. • Global states. • Long methods. • Large classes. > • Hard to maintain. • High learning curve. • Stability issues. • You can never expect problems before they occur Sunday, October 6, 13
  • 10. Test-Driven Development To The Recuse! Methodology for using automated unit tests to drive software design, quality and stability. Sunday, October 6, 13
  • 11. Test-Driven Development To The Recuse! How it’s done : • First the developer writes a failing test case that defines a desired functionality to the software. • Makes the code pass those tests. • Refactor the code to meet standards. Sunday, October 6, 13
  • 12. Seems Great But How Much Longer Does TDD Takes??? My experience: • Initial progress will be slower. • Greater consistency. • Long tern cost is drastically lower • After getting used to it, you can write TDD faster (-: Studies: • Takes 15-30% longer. • 45-80% less bugs. • Fixing bugs later on is dramatically faster. Sunday, October 6, 13
  • 13. The Three Rules of TDD Rule #1 Your code should always fail before you implement the code Rule #2 Implement the simplest code possible to pass your tests. Rule #3 Refactor, refactor and refractor - There is no shame in refactoring. Sunday, October 6, 13
  • 14. BDD (Behavior-Driven Development) Test-Driven Development Sunday, October 6, 13
  • 15. BDD (Behavior-Driven Development) Test-Driven Development What exactly are we testing?! Sunday, October 6, 13
  • 16. BDD (Behavior-Driven Development) • Originally started in 2003 by Dan North, author of JBehave, the first BDD tool. • Based on the TDD methodology. • Aims to provide tools for both developers and business (e.g. product manager, etc.) to share development process together. • The steps of BDD : • Developers and business personas write specification together. • Developer writes tests based on specs and make them fail. • Write code to pass those tests. • Refactor, refactor, refactor... Sunday, October 6, 13
  • 17. BDD (Behavior-Driven Development) Feature: ls In order to see the directory structure As a UNIX user I need to be able to list the current directory's contents Scenario: List 2 files in a directory Given I am in a directory "test" And I have a file named "foo" And I have a file named "bar" When I run "ls" Then I should get: """ bar foo """ * Behat example Sunday, October 6, 13
  • 18. Main Test Types • Unit Testing • Integration Testing • Functional Testing Sunday, October 6, 13
  • 19. Challenges Testing PHP • You cannot mock global functions in PHP since they are immutable. • Procedural code is hard to mock and be tested. Sunday, October 6, 13
  • 20. TDD using PHPUnit PHPUnit is a popular PHP unit testing framework designed for making unit testing easy in PHP. PHPUnit Main features: • Supports both TDD style assertions. • Support multiple output formats like jUnit, JSON, TAP. • Proper exit status for CI support (using jUnit for test results and clover for code coverage report). • Supports multiple code coverage report formats like HTML, JSON, PHP serialized and clover. • Built-in assertions and matchers. Sunday, October 6, 13
  • 21. TDD using PHPUnit Installing PHPUnit $ pear config-set auto_discover 1 $ pear install pear.phpunit.de/PHPUnit Install mocha globally using pear: $ composer global require ‘phpunit/phpunit=3.8.*’ Install mocha globally using composer: $ wget https://phar.phpunit.de/phpunit.phar $ chmod +x phpunit.phar $ mv phpunit.phar /usr/local/bin/phpunit Download the PHP archive: Sunday, October 6, 13
  • 22. TDD using PHPUnit Basic test: Run it.. $ phpunit UserTest.php PHPUnit 3.7.22 by Sebastian Bergmann. ... Time: 0 seconds, Memory: 2.50Mb OK (1 test, 1 assertion) class UserSpec extends PHPUnit_Framework_TestCase { protected $invalidMail = 'invalid-mail'; public function testThatFilterVarReturnsFalseWhenInvalid() { $this->assertFalse(filter_var($this->invalidMail, FILTER_VALIDATE_EMAIL)); } } Sunday, October 6, 13
  • 23. Back to our code Sunday, October 6, 13
  • 24. First, Let’s Write The Tests! function user($username, $firstName, $lastName, $mail) { if (!$firstName || !$lastName) { throw new Exception('First or last name are not valid'); } else if(!is_string($mail) && !filter_var($mail, FILTER_VALIDATE_EMAIL)) { throw new Exception('Mail is not valid'); } else if(!$username) { throw new Exception('Username is not valid'); } $userServer = new UserServer(); try { $res = $userServer->exec(array( 'fullName' => $firstName . ' ' . $lastName, 'username' => $username, 'mail' => $mail )); if ($res->code !== 200) { $message = 'Failed saving user to server'; } $message = 'Success!'; } catch(Exception $e) { $message = 'Failed accessing user system'; } echo $message; } Sunday, October 6, 13
  • 25. First, Let’s Write The Tests! What to test in our case: • Validations. • Full name getter. • Post user save actions. What not to test : • UserServer object (-: we should isolate our code and test it only. Sunday, October 6, 13
  • 26. First, Let’s Write The Tests! class UserSpec extends PHPUnit_Framework_TestCase { protected $user; protected $userServerMock; protected $goodResponse; public function setUp() { $this->goodResponse = new stdClass(); $this->goodResponse->code = 200; $this->userServerMock = $this->getMock('UserServer', array('exec')); $this->user = new User('anakin', 'Anakin', 'Skywalker', 'anakin@wix.com', $this- >userServerMock); } /** * @expectedException Exception */ public function testThatInvalidMailThrows() { $this->user->setMail('invalid-mail'); } public function testThatValidMailWorks() { $validMail = 'me@mail.com'; $this->user->setMail($validMail); $this->assertEquals($validMail, $this->user->getMail()); } Sunday, October 6, 13
  • 27. First, Let’s Write The Tests! public function testThatUserServerExecIsCalledWhenSavingAUser() { $this->userServerMock->expects($this->once()) ->method('exec') ->will($this->returnValue($this->goodResponse)); $this->user->save(); } public function testThatFullNameIsConcatinatedCorrcetly() { $this->userServerMock->expects($this->once()) ->method('exec') ->with($this->callback(function($data) { return $data['fullName'] === 'Anakin Skywalker'; })) ->will($this->returnValue($this->goodResponse)); $this->user->save(); } } Sunday, October 6, 13
  • 28. Run those tests Sunday, October 6, 13
  • 29. Now, Let’s Write The Code class User { protected $username; protected $firstName; protected $lastName; protected $mail; protected $userServer; public function __construct($username, $firstName, $lastName, $mail, $userServer) { $this->username = $username; $this->firstName = $firstName; $this->lastName = $lastName; $this->setMail($mail); $this->userServer = $userServer; } public function setMail($mail) { if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) { throw new Exception('Mail is not valid'); } $this->mail = $mail; return $this; } Sunday, October 6, 13
  • 30. Now, Let’s Write The Code public function getMail() { return $this->mail; } protected function getFullName() { return $this->firstName . ' ' . $this->lastName; } public function getUsername() { return $this->username; } public function save() { $response = $this->userServer->exec(array( 'fullName' => $this->getFullName(), 'mail' => $this->getMail(), 'username' => $this->getUsername() )); if (!$this->isSuccessful($response->code)) { return 'Failed saving to user server'; } return 'Success!'; } protected function isSuccessful($code) { return $code >= 200 && $code < 300; } } Sunday, October 6, 13
  • 32. Running The Tests PHPUnit tests can run and provide different types of results: • CLI - as demonstrated before using the “phpunit” command. • CI (e.g. jUnit) - (e.g. $ phpunit --log-junit=[file]). • HTML||clover code coverage (e.g. $ phpunit --coverage-html=[dir]). • Many other formats (JSON, TAP, Serialized PHP and more). Sunday, October 6, 13
  • 33. Benefits of Testing Your Code • Short feedback/testing cycle. • High code coverage of tests that can be at run any time to provide feedback that the software is functioning. • Provides detailed spec/docs of the application. • Less time spent on debugging and refactoring. • Know what breaks early on. • Enforces code quality (decoupled) and simplicity. • Help you focus on writing one job code units. Sunday, October 6, 13