SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
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
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
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
 
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
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
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
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
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
 

Kürzlich hochgeladen (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
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
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
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
 
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.
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
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
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
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
 

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