SlideShare une entreprise Scribd logo
1  sur  34
Télécharger pour lire hors ligne
PHPUNIT BEST PRACTICES


      Volker Dusch / @_ _edorian
ABOUT ME
Software Engineer
PHP since 11 years
CI
CleanCode
DevOps
TDD
Shipping
Bullet points
INSTEAD OF ME
WORKING FOR




ResearchGate gives science back to the people who make it happen.
  We help researchers build reputation and accelerate scientific
                           progress.
                         On their terms.
GET IN TOUCH
stackoverflow:



Twitter: @__edorian
g+: Volker Dusch
IRC: edorian
Mail: php@wallbash.com
AGENDA
Some practices I value
Your mileage may vary
By no means complete
WRITE TESTS
It's sounds obvious but getting started sometimes is the hardest part!
THE FASTEST THING YOU CAN DO
ht=cr - saigpoetcm|ge 'oi: |w -`
 is`ul s tgn.rjc.o    rp Lgn' c l;
ts $is-q1| eh "rnpg err"
 et ht e   | co Fotae ro!


          Staging server
          Testing your builds
          All without even touching PHPUnit
dt=lgnts&asotscr&sf"crTkn
 aa"oi=etpswr=euecr=$sfoe
ht=cr - PS - saigpoetcm|ge 'el,tsue'|w -`
 is`ul X OT d tgn.rjc.o  rp Hlo etsr  c l;
ts $is-q1| eh "oi err"
 et ht e   | co Lgn ro!
LET'S GO
UPGRADE TO PHPUNIT 3.7
      EASE INSTALLTION
PHAR
we ht:/erppntd/e/hui.hr
 gt tp/pa.hui.egtppntpa
cmd+ ppntpa
 ho x hui.hr
.ppntpa -vrin
 /hui.hr -eso


                   or
we ht:/erppntd/e/hui.hr
 gt tp/pa.hui.egtppntpa
cmd+ ppntpa
 ho x hui.hr
m ppntpa /s/oa/i/hui
 v hui.hr urlclbnppnt
ppnt-vrin
 hui -eso
COMPOSER
        The Dependency Manager for PHP




With the best from zypper, bundler, pip, gem and npm
PHPUNIT PER PROJECT
cmoe.sn
 opsrjo
{
  "eur-e" {
   rqiedv:
    "hui/hui" ".."
    ppntppnt: 37*
  }
}



cmoe isal
 opsr ntl
.vno/i/hui -vrin
 /edrbnppnt -eso
PHPUNIT GLOBAL INSTALL
{
    "eur" {
     rqie:
       "hui/hui" ".."
       ppntppnt: 37*
    },
    "ofg:{
     cni"
       "i-i" "urlclbn"
       bndr: /s/oa/i/
    }
}



sd ppcmoe isal
 uo h opsr ntll
ppni -vrin
 huut -eso
PEAR
pear config-set auto_discover 1
pear install pear.phpunit.de/PHPUnit
phpunit --version
USE SPECIFIC ASSERTIONS
              PHPUnit ships with over 90 assertions.
http://www.phpunit.de/manual/current/en/appendixes.assertions.html
         Use them to get pretty and helpful error messages.
assertTrue vs assertInstanceOf
$o =nwSdls(;
 fo  e tCas)
$hs>setre$o isacO Cutbe;
 ti-asrTu(fo ntnef onal)


            “Failed asserting that false is true.”
$o =nwSdls(;
 fo  e tCas)
$hs>setntnef'onal' $o)
 ti-asrIsacO(Cutbe, fo;


                    “Failed asserting that
     stdClass() is an instance of interface 'Countable'.”
assertEquals vs assertJsonStringEqualsJsonFile
                  assertEquals
 Fie asrigta tosrnsaeeul
  ald setn ht w tig r  qa.
 --Epce
  -  xetd
 ++Ata
  +  cul
 @ @
  @ @
 -{"ofrne:"ODM,"ak:"HUi" "SN:"paety,"huot
  '  Cneec" FSE" Tl"  PPnt, JO" Aprnl" Sotu"
 :"ekn"}
    Jnis '
 +{"ofrne:"ODM,"ak:"HUi" "SN:"paety,"huot
  '  Cneec" FSE" Tl"  PPnt, JO" Aprnl" Sotu"
 :"usn }
    Hdo" '
assertEquals vs assertJsonStringEqualsJsonFile
            assertJsonStringEqualsJsonFile
 Fie asrigta toojcsaeeul
  ald setn ht w   bet r qa.
 --Epce
  -  xetd
 ++Ata
  +  cul
 @ @
  @ @
  sdls Ojc (
   tCas bet
     'ofrne = 'ODM
      Cneec' > FSE'
     'ak = 'HUi'
      Tl' > PPnt
     'SN = 'paety
      JO' > Aprnl'
 -   'huot = 'ekn'
      Sotu' > Jnis
 +   'huot = 'usn
      Sotu' > Hdo'
  )
HAVE A FAST TEST SUITE
  If it takes to long to run your tests you won't do it
SEPERATE YOUR TESTS
http://elblinkin.info/2012/03/goldilocks-on-test-sizes/
BY FOLDER STRUCTURE
.
|-sc
 -  r
| `-fo
    - o
|     `-br
       - a
|        `-Bzpp
         -  a.h
`-tss
 -  et
   |-fntoa
    - ucinl
   |-itgain
    - nerto
   |-ui
    - nt
   |  `-fo
       - o
   |     `-br
         -  a
   |       `-Bzetpp
            - aTs.h
   `-wb
    - e



ppnttssui
 hui et/nt
BY CONFIG FILE
<etuts
 tssie>
  <etut nm=Ui"sfi=Ts.h"
   tssie ae"nt ufx"etpp>
   <ietr>et<drcoy
    drcoytss/ietr>
  <tssie
   /etut>
  <etut nm=Itgain sfi=Ts.nerto.h"
   tssie ae"nerto" ufx"etItgainpp>
   <ietr>et<drcoy
    drcoytss/ietr>
  <tssie
   /etut>
<tssie>
 /etuts



ppnt-tssieUi
 hui -etut nt
OR HOWEVER YOU SEE FIT
Use @group
Use @filter and naming conventions
BOOTSTRAP ONLY WHAT YOU NEED
                 You can use a test listener:
    http://www.phpunit.de/manual/current/en/extending-
phpunit.html#extending-phpunit.PHPUnitFrameworkTestListener
 pbi fnto satetut(HUi_rmwr_etut $ut)
  ulc ucin trTsSiePPntFaeokTsSie sie
 {
   / Js a eapeo wa i psil
    / ut n xml  f ht s osbe
   rqie_DR_.$ut-gtae).'otta.h'
    eur _I_    sie>eNm(     Bosrppp;
 }
HOW MANY TESTS?




                   Web: 7
                   Funtional: One per feature
                   Integration: One per 3 classes
                   Unit: Find a balance

*totally made up numbers to drive home the point I'm trying to make
WEB TESTS?
behat (mink) for js-through-the-server testing - Great for testing
your whole stack
   Really hard to maintain
   Mink relives some of the pain
Test through your front controller instead of the webserver with
behat or phpunit
   Faster, easier once set up
TEST CLASSES,
                 NOT METHODS
 > Unit testing, in PHP, is about testing the observable behaviors of a
                                  class!
Observable from the outside! Nobody cares about the internal state of
      a class if it never changes the outcome of a method call.
SAMPLE
                   What should we test there?
 pbi fnto stau(vle {
  ulc ucin eVle$au)
   $hs>au =$au;
   ti-vle   vle
 }

 pbi fnto eeue){
  ulc ucin xct(
   i ($hs>au){
    f !ti-vle
     trwnwEcpin"oVle n go";
      ho e  xeto(N  au, o od)
   }
   rtr $au *1;/ bsns lgc
    eun vle  0  / uies oi
 }


If we don't call setValue calling execute will throw an exception
If we do call setValue calling execute will return the computed
result.
So we are testing two behaviors of your class and not the methods in
isolation!
RELEVANT BEHAVIORS
                          What to test then?
return values
    pbi fcinclisoaehi(dgesaehi){
     ulc uto ecuTFrnet$ereFrnet
      rtr (dgesaehi -3)*5⁄9
       eun $ereFrnet  2    ;
    }


method calls to other objects
    pbi fcinsoCr){
     ulc uto tpa(
      $hs>adra-egg(;
       ti-hnbek>nae)
      $hs>nie>hton)
       ti-egn-sudw(;
    }


Global state
    pbi fcinaodhshrPsil(lgesg){
     ulc uto viTiWeeosbe$oMsae
      fl_u_otnssai:$OFL,$oMsae FL_PED;
       ieptcnet(ttc:LGIE lgesg, IEAPN)
      $SSIN'ocls]+
       _ESO[lgal'+;
    }
DON'T TEST GETTERS AND SETTERS
              One test case per behavior
You waste time
Your code coverage reports won't tell you about dead code
If they don't impact the outcome delete them
QUESTIONS?
 “The secret in testing is in writing testable code”
                 - Miško Hevery


              Additional resources
"The Clean Code Talks -- Unit Testing
How to Write Clean, Testable Code
The Clean Code Talks - Don't Look For Things!
Flaw: Brittle Global State & Singletons
static considered harmful
The UNIT in unit testing
An introduction to PHPUnits @covers annotation
THANK YOU
PhpUnit Best Practices

Contenu connexe

Tendances

Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDPaweł Michalik
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentationnicobn
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitMichelangelo van Dam
 
Beginning PHPUnit
Beginning PHPUnitBeginning PHPUnit
Beginning PHPUnitJace Ju
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingRam Awadh Prasad, PMP
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEnterprise PHP Center
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)ENDelt260
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring QualityKent Cowgill
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With PythonSiddhi
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Michelangelo van Dam
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013Michelangelo van Dam
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2Yi-Huan Chan
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit TestDavid Xie
 

Tendances (20)

Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDD
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Phpunit testing
Phpunit testingPhpunit testing
Phpunit testing
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnit
 
Beginning PHPUnit
Beginning PHPUnitBeginning PHPUnit
Beginning PHPUnit
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
 
Unit testing
Unit testingUnit testing
Unit testing
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring Quality
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
 

En vedette

En vedette (20)

B M Social Media Fortune 100
B M Social Media Fortune 100B M Social Media Fortune 100
B M Social Media Fortune 100
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
 
Déployer avec les tests
Déployer avec les testsDéployer avec les tests
Déployer avec les tests
 
Cake php + php unitによる実践的ユニットテスト
Cake php + php unitによる実践的ユニットテストCake php + php unitによる実践的ユニットテスト
Cake php + php unitによる実践的ユニットテスト
 
PhpBB meets Symfony2
PhpBB meets Symfony2PhpBB meets Symfony2
PhpBB meets Symfony2
 
Behat bdd training (php) course slides pdf
Behat bdd training (php) course slides pdfBehat bdd training (php) course slides pdf
Behat bdd training (php) course slides pdf
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
 
FizzBuzzではじめるテスト
FizzBuzzではじめるテストFizzBuzzではじめるテスト
FizzBuzzではじめるテスト
 
8時間耐久PHPUnitの教室
8時間耐久PHPUnitの教室8時間耐久PHPUnitの教室
8時間耐久PHPUnitの教室
 
Chase A
Chase AChase A
Chase A
 
PPGNY Membership Drive
PPGNY Membership DrivePPGNY Membership Drive
PPGNY Membership Drive
 
Lucius M
Lucius MLucius M
Lucius M
 
Dolby1
Dolby1Dolby1
Dolby1
 
Comic
ComicComic
Comic
 
Your (coding) standards matter
Your (coding) standards matterYour (coding) standards matter
Your (coding) standards matter
 
Livejournal
LivejournalLivejournal
Livejournal
 
Food Rules
Food RulesFood Rules
Food Rules
 
Online distance PG Diploma courses from MIT Pune
Online distance PG Diploma courses from MIT PuneOnline distance PG Diploma courses from MIT Pune
Online distance PG Diploma courses from MIT Pune
 
Kelley
KelleyKelley
Kelley
 
Add topic
Add topicAdd topic
Add topic
 

Similaire à PhpUnit Best Practices

The State of PHPUnit
The State of PHPUnitThe State of PHPUnit
The State of PHPUnitEdorian
 
The State of PHPUnit
The State of PHPUnitThe State of PHPUnit
The State of PHPUnitEdorian
 
The state of PHPUnit
The state of PHPUnitThe state of PHPUnit
The state of PHPUnitEdorian
 
Automated tests - facts and myths
Automated tests - facts and mythsAutomated tests - facts and myths
Automated tests - facts and mythsWojciech Sznapka
 
Testing TYPO3 Applications
Testing TYPO3 ApplicationsTesting TYPO3 Applications
Testing TYPO3 ApplicationsAndré Wuttig
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitJames Fuller
 
Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )Joseph Scott
 
Making the most of 2.2
Making the most of 2.2Making the most of 2.2
Making the most of 2.2markstory
 
Theme Development and Customization
Theme Development and CustomizationTheme Development and Customization
Theme Development and CustomizationAniket Pant
 
utPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLutPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLSteven Feuerstein
 
Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaNginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaTony Fabeen
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scriptingTony Fabeen
 
Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony componentsMichael Peacock
 
Alexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersAlexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersDevDay Dresden
 
An Introduction to CSS Preprocessors
An Introduction to CSS PreprocessorsAn Introduction to CSS Preprocessors
An Introduction to CSS PreprocessorsMiloš Sutanovac
 
Javascript fundamentals for php developers
Javascript fundamentals for php developersJavascript fundamentals for php developers
Javascript fundamentals for php developersChris Ramakers
 
Introduction to Ansible
Introduction to AnsibleIntroduction to Ansible
Introduction to AnsibleMattias Gees
 
Learn Frontend Testing
Learn Frontend TestingLearn Frontend Testing
Learn Frontend TestingRyan Roemer
 

Similaire à PhpUnit Best Practices (20)

The State of PHPUnit
The State of PHPUnitThe State of PHPUnit
The State of PHPUnit
 
The State of PHPUnit
The State of PHPUnitThe State of PHPUnit
The State of PHPUnit
 
The state of PHPUnit
The state of PHPUnitThe state of PHPUnit
The state of PHPUnit
 
Automated tests - facts and myths
Automated tests - facts and mythsAutomated tests - facts and myths
Automated tests - facts and myths
 
Testing TYPO3 Applications
Testing TYPO3 ApplicationsTesting TYPO3 Applications
Testing TYPO3 Applications
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnit
 
Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )
 
Php101
Php101Php101
Php101
 
Making the most of 2.2
Making the most of 2.2Making the most of 2.2
Making the most of 2.2
 
Theme Development and Customization
Theme Development and CustomizationTheme Development and Customization
Theme Development and Customization
 
utPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLutPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQL
 
Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaNginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with Lua
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scripting
 
Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony components
 
Alexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersAlexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for Developers
 
An Introduction to CSS Preprocessors
An Introduction to CSS PreprocessorsAn Introduction to CSS Preprocessors
An Introduction to CSS Preprocessors
 
Javascript fundamentals for php developers
Javascript fundamentals for php developersJavascript fundamentals for php developers
Javascript fundamentals for php developers
 
Introduction to Ansible
Introduction to AnsibleIntroduction to Ansible
Introduction to Ansible
 
Learn Frontend Testing
Learn Frontend TestingLearn Frontend Testing
Learn Frontend Testing
 

Plus de Edorian

Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principlesEdorian
 
Nginx - The webserver you might actually like
Nginx - The webserver you might actually likeNginx - The webserver you might actually like
Nginx - The webserver you might actually likeEdorian
 
From dev to ops and beyond - getting it done
From dev to ops and beyond - getting it doneFrom dev to ops and beyond - getting it done
From dev to ops and beyond - getting it doneEdorian
 
Code review in practice
Code review in practiceCode review in practice
Code review in practiceEdorian
 
Nginx & php fpm - the webserver you might actually like - php usergroup berlin
Nginx & php fpm - the webserver you might actually like - php usergroup berlinNginx & php fpm - the webserver you might actually like - php usergroup berlin
Nginx & php fpm - the webserver you might actually like - php usergroup berlinEdorian
 
Clean code is not the goal - working software is
Clean code is not the goal - working software isClean code is not the goal - working software is
Clean code is not the goal - working software isEdorian
 
Nginx The webserver you might actually like
Nginx   The webserver you might actually likeNginx   The webserver you might actually like
Nginx The webserver you might actually likeEdorian
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesEdorian
 
php unconference Europa: Clean code - Stop wasting my time
php unconference Europa: Clean code - Stop wasting my timephp unconference Europa: Clean code - Stop wasting my time
php unconference Europa: Clean code - Stop wasting my timeEdorian
 
Clean Code: Stop wasting my time
Clean Code: Stop wasting my timeClean Code: Stop wasting my time
Clean Code: Stop wasting my timeEdorian
 

Plus de Edorian (10)

Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
 
Nginx - The webserver you might actually like
Nginx - The webserver you might actually likeNginx - The webserver you might actually like
Nginx - The webserver you might actually like
 
From dev to ops and beyond - getting it done
From dev to ops and beyond - getting it doneFrom dev to ops and beyond - getting it done
From dev to ops and beyond - getting it done
 
Code review in practice
Code review in practiceCode review in practice
Code review in practice
 
Nginx & php fpm - the webserver you might actually like - php usergroup berlin
Nginx & php fpm - the webserver you might actually like - php usergroup berlinNginx & php fpm - the webserver you might actually like - php usergroup berlin
Nginx & php fpm - the webserver you might actually like - php usergroup berlin
 
Clean code is not the goal - working software is
Clean code is not the goal - working software isClean code is not the goal - working software is
Clean code is not the goal - working software is
 
Nginx The webserver you might actually like
Nginx   The webserver you might actually likeNginx   The webserver you might actually like
Nginx The webserver you might actually like
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principles
 
php unconference Europa: Clean code - Stop wasting my time
php unconference Europa: Clean code - Stop wasting my timephp unconference Europa: Clean code - Stop wasting my time
php unconference Europa: Clean code - Stop wasting my time
 
Clean Code: Stop wasting my time
Clean Code: Stop wasting my timeClean Code: Stop wasting my time
Clean Code: Stop wasting my time
 

Dernier

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 

Dernier (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 

PhpUnit Best Practices

  • 1. PHPUNIT BEST PRACTICES Volker Dusch / @_ _edorian
  • 2. ABOUT ME Software Engineer PHP since 11 years CI CleanCode DevOps TDD Shipping Bullet points
  • 4. WORKING FOR ResearchGate gives science back to the people who make it happen. We help researchers build reputation and accelerate scientific progress. On their terms.
  • 5. GET IN TOUCH stackoverflow: Twitter: @__edorian g+: Volker Dusch IRC: edorian Mail: php@wallbash.com
  • 6. AGENDA Some practices I value Your mileage may vary By no means complete
  • 7. WRITE TESTS It's sounds obvious but getting started sometimes is the hardest part!
  • 8. THE FASTEST THING YOU CAN DO ht=cr - saigpoetcm|ge 'oi: |w -` is`ul s tgn.rjc.o rp Lgn' c l; ts $is-q1| eh "rnpg err" et ht e | co Fotae ro! Staging server Testing your builds All without even touching PHPUnit dt=lgnts&asotscr&sf"crTkn aa"oi=etpswr=euecr=$sfoe ht=cr - PS - saigpoetcm|ge 'el,tsue'|w -` is`ul X OT d tgn.rjc.o rp Hlo etsr c l; ts $is-q1| eh "oi err" et ht e | co Lgn ro!
  • 10. UPGRADE TO PHPUNIT 3.7 EASE INSTALLTION
  • 11. PHAR we ht:/erppntd/e/hui.hr gt tp/pa.hui.egtppntpa cmd+ ppntpa ho x hui.hr .ppntpa -vrin /hui.hr -eso or we ht:/erppntd/e/hui.hr gt tp/pa.hui.egtppntpa cmd+ ppntpa ho x hui.hr m ppntpa /s/oa/i/hui v hui.hr urlclbnppnt ppnt-vrin hui -eso
  • 12. COMPOSER The Dependency Manager for PHP With the best from zypper, bundler, pip, gem and npm
  • 13. PHPUNIT PER PROJECT cmoe.sn opsrjo { "eur-e" { rqiedv: "hui/hui" ".." ppntppnt: 37* } } cmoe isal opsr ntl .vno/i/hui -vrin /edrbnppnt -eso
  • 14. PHPUNIT GLOBAL INSTALL { "eur" { rqie: "hui/hui" ".." ppntppnt: 37* }, "ofg:{ cni" "i-i" "urlclbn" bndr: /s/oa/i/ } } sd ppcmoe isal uo h opsr ntll ppni -vrin huut -eso
  • 15. PEAR pear config-set auto_discover 1 pear install pear.phpunit.de/PHPUnit phpunit --version
  • 16. USE SPECIFIC ASSERTIONS PHPUnit ships with over 90 assertions. http://www.phpunit.de/manual/current/en/appendixes.assertions.html Use them to get pretty and helpful error messages.
  • 17. assertTrue vs assertInstanceOf $o =nwSdls(; fo e tCas) $hs>setre$o isacO Cutbe; ti-asrTu(fo ntnef onal) “Failed asserting that false is true.” $o =nwSdls(; fo e tCas) $hs>setntnef'onal' $o) ti-asrIsacO(Cutbe, fo; “Failed asserting that stdClass() is an instance of interface 'Countable'.”
  • 18. assertEquals vs assertJsonStringEqualsJsonFile assertEquals Fie asrigta tosrnsaeeul ald setn ht w tig r qa. --Epce - xetd ++Ata + cul @ @ @ @ -{"ofrne:"ODM,"ak:"HUi" "SN:"paety,"huot ' Cneec" FSE" Tl" PPnt, JO" Aprnl" Sotu" :"ekn"} Jnis ' +{"ofrne:"ODM,"ak:"HUi" "SN:"paety,"huot ' Cneec" FSE" Tl" PPnt, JO" Aprnl" Sotu" :"usn } Hdo" '
  • 19. assertEquals vs assertJsonStringEqualsJsonFile assertJsonStringEqualsJsonFile Fie asrigta toojcsaeeul ald setn ht w bet r qa. --Epce - xetd ++Ata + cul @ @ @ @ sdls Ojc ( tCas bet 'ofrne = 'ODM Cneec' > FSE' 'ak = 'HUi' Tl' > PPnt 'SN = 'paety JO' > Aprnl' - 'huot = 'ekn' Sotu' > Jnis + 'huot = 'usn Sotu' > Hdo' )
  • 20. HAVE A FAST TEST SUITE If it takes to long to run your tests you won't do it
  • 22. BY FOLDER STRUCTURE . |-sc - r | `-fo - o | `-br - a | `-Bzpp - a.h `-tss - et |-fntoa - ucinl |-itgain - nerto |-ui - nt | `-fo - o | `-br - a | `-Bzetpp - aTs.h `-wb - e ppnttssui hui et/nt
  • 23. BY CONFIG FILE <etuts tssie> <etut nm=Ui"sfi=Ts.h" tssie ae"nt ufx"etpp> <ietr>et<drcoy drcoytss/ietr> <tssie /etut> <etut nm=Itgain sfi=Ts.nerto.h" tssie ae"nerto" ufx"etItgainpp> <ietr>et<drcoy drcoytss/ietr> <tssie /etut> <tssie> /etuts ppnt-tssieUi hui -etut nt
  • 24. OR HOWEVER YOU SEE FIT Use @group Use @filter and naming conventions
  • 25. BOOTSTRAP ONLY WHAT YOU NEED You can use a test listener: http://www.phpunit.de/manual/current/en/extending- phpunit.html#extending-phpunit.PHPUnitFrameworkTestListener pbi fnto satetut(HUi_rmwr_etut $ut) ulc ucin trTsSiePPntFaeokTsSie sie { / Js a eapeo wa i psil / ut n xml f ht s osbe rqie_DR_.$ut-gtae).'otta.h' eur _I_ sie>eNm( Bosrppp; }
  • 26. HOW MANY TESTS? Web: 7 Funtional: One per feature Integration: One per 3 classes Unit: Find a balance *totally made up numbers to drive home the point I'm trying to make
  • 27. WEB TESTS? behat (mink) for js-through-the-server testing - Great for testing your whole stack Really hard to maintain Mink relives some of the pain Test through your front controller instead of the webserver with behat or phpunit Faster, easier once set up
  • 28. TEST CLASSES, NOT METHODS > Unit testing, in PHP, is about testing the observable behaviors of a class! Observable from the outside! Nobody cares about the internal state of a class if it never changes the outcome of a method call.
  • 29. SAMPLE What should we test there? pbi fnto stau(vle { ulc ucin eVle$au) $hs>au =$au; ti-vle vle } pbi fnto eeue){ ulc ucin xct( i ($hs>au){ f !ti-vle trwnwEcpin"oVle n go"; ho e xeto(N au, o od) } rtr $au *1;/ bsns lgc eun vle 0 / uies oi } If we don't call setValue calling execute will throw an exception If we do call setValue calling execute will return the computed result. So we are testing two behaviors of your class and not the methods in isolation!
  • 30. RELEVANT BEHAVIORS What to test then? return values pbi fcinclisoaehi(dgesaehi){ ulc uto ecuTFrnet$ereFrnet rtr (dgesaehi -3)*5⁄9 eun $ereFrnet 2 ; } method calls to other objects pbi fcinsoCr){ ulc uto tpa( $hs>adra-egg(; ti-hnbek>nae) $hs>nie>hton) ti-egn-sudw(; } Global state pbi fcinaodhshrPsil(lgesg){ ulc uto viTiWeeosbe$oMsae fl_u_otnssai:$OFL,$oMsae FL_PED; ieptcnet(ttc:LGIE lgesg, IEAPN) $SSIN'ocls]+ _ESO[lgal'+; }
  • 31. DON'T TEST GETTERS AND SETTERS One test case per behavior You waste time Your code coverage reports won't tell you about dead code If they don't impact the outcome delete them
  • 32. QUESTIONS? “The secret in testing is in writing testable code” - Miško Hevery Additional resources "The Clean Code Talks -- Unit Testing How to Write Clean, Testable Code The Clean Code Talks - Don't Look For Things! Flaw: Brittle Global State & Singletons static considered harmful The UNIT in unit testing An introduction to PHPUnits @covers annotation