SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

Destacado (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
 

Similar a 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
 

Similar a 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
 

Más 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
 

Más 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
 

Último

Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
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
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
[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
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
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
 
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
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
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
 
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
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
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
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
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...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
[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
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
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...
 
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
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
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
 
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
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
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
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 

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