SlideShare a Scribd company logo
1 of 25
by Silviu Butnariu (sbutnariu@pentalog.fr)
What’s that?
 Unit testing = testing bunches of code, not the whole

application
 PhpUnit was created by Sebastian Bergamann
 It’s part of xUnit family – most used unit testers

 Used for automatic tests – makes the machine do the

work
What are the benefits
of unit testing?
 Uncover bugs easier – good tests go trough all possible

program paths
 Assure high code coverage – measurable code quality

indicator
 Faster than manual testing
 Suitable for teamwork
Installing PhpUnit
 With PEAR:

pear config-set auto_discover 1
pear install phpunit/PHPUnit
 With composer (dependency manager for php); just

add to composer.json:
{ "require-dev": { "phpunit/phpunit": "3.7.*" } }
and update the composer
Basic test
Test result notations
. – success
F – failure
E – error
I – incomplete
S - skipped
Assertions
 Helper functions that compare an expected result with
-

the actual one:
assertEquals()
assertFalse()
assertArrayHasKey()
assertInstanceOf()
assertNotNull()
assertRegExp()
etc.
Dependency injection
 DI is a software pattern that allows the removal of

hard-coded dependencies
 Highly coupled dependencies – bad
 Loose coupled dependencies - awesome
 Improves code readability, reusability
DI guidelines
 Don’t use ‘new’
 Pass dependencies as method parameters
 DI allows real unit testing, by separating modules
 Read the DI best practices 
Mocking objects
 Creating fake objects that act in a predefined and

predictable way
Stubbing methods
 In close relation to mocking
 Stubbing implies faking a method from the mock

object
Static methods
 Avoid static methods

Can’t mock
static calls to
outside classes!
Annotations
 These syntactic metadata are used for specifying
-

some special case behaviors
@covers
@test
@dataProvider
@expectedException
@group
etc.
Data Provider
 Allows to bunch up more test cases into one, thus

reducing code duplicity
Testing exceptions
setUp & tearDown
 setUp(), tearDown() – executed once for each test method
 setUpBeforeClass(), tearDownAfterClass() - called before the first

test of the test case and after the last test
DB testing
 Need extension: pear install phpunit/DbUnit
 Supported dbs: mysql, postgre, oracle, sqlite
 There are 4 stages of db testing:
- set up fixture
- exercise SUT
- verify outcome
- teardown
 Important methods:
- getConnection() - connection data (host,db,pass)
- getDataSet() – defines state of DB before each test
DB testing
 Once setting up the ‘fake’ db connection tests can be

executed to check queries

 The db changes that occur during the tests don’t persist
 Can verify number of rows after insertion, check query

results, etc.

 This is the safest way of fully testing an application

(versus mocking db connection)
Skeleton Generator
 Automatically generates test classes based on

assertions in the code
IDE integration
 Integrated in most ides: Eclipse, NetBeans,

PhpStorm, etc
Code coverage
 Generating statistics with naked PhpUnit
 phpunit -c app/ --coverage-html={foldername}
Code coverage
 FFFFFFF
Documentation
 http://phpunit.de/manual/3.7/en/
Q&A
THANKS !!!

More Related Content

What's hot

Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...
Timo Stollenwerk
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
nicobn
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
Tricode (part of Dept)
 

What's hot (20)

Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
Python unittest
Python unittestPython unittest
Python unittest
 
Day1_Apache_JMeter_Overview
Day1_Apache_JMeter_OverviewDay1_Apache_JMeter_Overview
Day1_Apache_JMeter_Overview
 
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit TestingPython Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit Testing
 
Python testing
Python  testingPython  testing
Python testing
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPress
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
Phpunit testing
Phpunit testingPhpunit testing
Phpunit testing
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Unit testing using jasmine in Javascript
Unit testing using jasmine in JavascriptUnit testing using jasmine in Javascript
Unit testing using jasmine in Javascript
 
Unit Testing in WordPress
Unit Testing in WordPressUnit Testing in WordPress
Unit Testing in WordPress
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnit
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
 
NUnit Features Presentation
NUnit Features PresentationNUnit Features Presentation
NUnit Features Presentation
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to hero
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 

Viewers also liked

Tango argentino
Tango argentinoTango argentino
Tango argentino
sarapaol
 
Composition
CompositionComposition
Composition
kdxkid
 
Weather17th 20th
Weather17th 20thWeather17th 20th
Weather17th 20th
amykay16
 
Conditionals 100819134225-phpapp01
Conditionals 100819134225-phpapp01Conditionals 100819134225-phpapp01
Conditionals 100819134225-phpapp01
wil_4158
 
Weather 1st 11th
Weather 1st 11thWeather 1st 11th
Weather 1st 11th
amykay16
 
Estado da Arte HTML5
Estado da Arte HTML5Estado da Arte HTML5
Estado da Arte HTML5
MCM-IPG
 
Menkes bp dr.ricca
Menkes bp dr.riccaMenkes bp dr.ricca
Menkes bp dr.ricca
Sufya Anwar
 

Viewers also liked (20)

chapters
chapterschapters
chapters
 
IPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopIPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHop
 
Zendesk PRO Tips
Zendesk PRO TipsZendesk PRO Tips
Zendesk PRO Tips
 
About Me
About MeAbout Me
About Me
 
Tango argentino
Tango argentinoTango argentino
Tango argentino
 
Collaborative Filtering Survey
Collaborative Filtering SurveyCollaborative Filtering Survey
Collaborative Filtering Survey
 
Gami offshorent - executive overview
Gami   offshorent - executive overviewGami   offshorent - executive overview
Gami offshorent - executive overview
 
Minialbunatoyac
MinialbunatoyacMinialbunatoyac
Minialbunatoyac
 
Composition
CompositionComposition
Composition
 
Weather17th 20th
Weather17th 20thWeather17th 20th
Weather17th 20th
 
Path To Prosperity Small To Midsize Companies
Path To Prosperity Small To Midsize CompaniesPath To Prosperity Small To Midsize Companies
Path To Prosperity Small To Midsize Companies
 
Conditionals 100819134225-phpapp01
Conditionals 100819134225-phpapp01Conditionals 100819134225-phpapp01
Conditionals 100819134225-phpapp01
 
Weather 1st 11th
Weather 1st 11thWeather 1st 11th
Weather 1st 11th
 
Web 1.0,2.0 y 3.0
Web 1.0,2.0 y 3.0Web 1.0,2.0 y 3.0
Web 1.0,2.0 y 3.0
 
Twitter
TwitterTwitter
Twitter
 
Estado da Arte HTML5
Estado da Arte HTML5Estado da Arte HTML5
Estado da Arte HTML5
 
Menkes bp dr.ricca
Menkes bp dr.riccaMenkes bp dr.ricca
Menkes bp dr.ricca
 
Stop motion
Stop motionStop motion
Stop motion
 
Steaua bucuresti
Steaua bucurestiSteaua bucuresti
Steaua bucuresti
 
Lecturi
LecturiLecturi
Lecturi
 

Similar to Unit Testing in PHP

Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
varuntaliyan
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
Yi-Huan Chan
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
Priya Sharma
 

Similar to Unit Testing in PHP (20)

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
 
Zend Framework 2 - PHPUnit
Zend Framework 2 - PHPUnitZend Framework 2 - PHPUnit
Zend Framework 2 - PHPUnit
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
 
Unit testing
Unit testingUnit testing
Unit testing
 
PHPUnit with CakePHP and Yii
PHPUnit with CakePHP and YiiPHPUnit with CakePHP and Yii
PHPUnit with CakePHP and Yii
 
Php unit (eng)
Php unit (eng)Php unit (eng)
Php unit (eng)
 
Automated tests to a REST API
Automated tests to a REST APIAutomated tests to a REST API
Automated tests to a REST API
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
 
Getting started with PHPUnit
Getting started with PHPUnitGetting started with PHPUnit
Getting started with PHPUnit
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Unit testing
Unit testingUnit testing
Unit testing
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 

More from Radu Murzea (7)

The World of StackOverflow
The World of StackOverflowThe World of StackOverflow
The World of StackOverflow
 
SymfonyCon 2015 - A symphony of developers
SymfonyCon 2015 - A symphony of developersSymfonyCon 2015 - A symphony of developers
SymfonyCon 2015 - A symphony of developers
 
The World of PHP PSR Standards
The World of PHP PSR StandardsThe World of PHP PSR Standards
The World of PHP PSR Standards
 
PHP 7 - A look at the future
PHP 7 - A look at the futurePHP 7 - A look at the future
PHP 7 - A look at the future
 
Hack programming language
Hack programming languageHack programming language
Hack programming language
 
Hack Programming Language
Hack Programming LanguageHack Programming Language
Hack Programming Language
 
HipHop Virtual Machine
HipHop Virtual MachineHipHop Virtual Machine
HipHop Virtual Machine
 

Recently uploaded

Recently uploaded (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.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
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 

Unit Testing in PHP

  • 1. by Silviu Butnariu (sbutnariu@pentalog.fr)
  • 2. What’s that?  Unit testing = testing bunches of code, not the whole application  PhpUnit was created by Sebastian Bergamann  It’s part of xUnit family – most used unit testers  Used for automatic tests – makes the machine do the work
  • 3. What are the benefits of unit testing?  Uncover bugs easier – good tests go trough all possible program paths  Assure high code coverage – measurable code quality indicator  Faster than manual testing  Suitable for teamwork
  • 4. Installing PhpUnit  With PEAR: pear config-set auto_discover 1 pear install phpunit/PHPUnit  With composer (dependency manager for php); just add to composer.json: { "require-dev": { "phpunit/phpunit": "3.7.*" } } and update the composer
  • 6. Test result notations . – success F – failure E – error I – incomplete S - skipped
  • 7. Assertions  Helper functions that compare an expected result with - the actual one: assertEquals() assertFalse() assertArrayHasKey() assertInstanceOf() assertNotNull() assertRegExp() etc.
  • 8. Dependency injection  DI is a software pattern that allows the removal of hard-coded dependencies  Highly coupled dependencies – bad  Loose coupled dependencies - awesome  Improves code readability, reusability
  • 9. DI guidelines  Don’t use ‘new’  Pass dependencies as method parameters  DI allows real unit testing, by separating modules  Read the DI best practices 
  • 10. Mocking objects  Creating fake objects that act in a predefined and predictable way
  • 11. Stubbing methods  In close relation to mocking  Stubbing implies faking a method from the mock object
  • 12. Static methods  Avoid static methods Can’t mock static calls to outside classes!
  • 13. Annotations  These syntactic metadata are used for specifying - some special case behaviors @covers @test @dataProvider @expectedException @group etc.
  • 14. Data Provider  Allows to bunch up more test cases into one, thus reducing code duplicity
  • 16. setUp & tearDown  setUp(), tearDown() – executed once for each test method  setUpBeforeClass(), tearDownAfterClass() - called before the first test of the test case and after the last test
  • 17. DB testing  Need extension: pear install phpunit/DbUnit  Supported dbs: mysql, postgre, oracle, sqlite  There are 4 stages of db testing: - set up fixture - exercise SUT - verify outcome - teardown  Important methods: - getConnection() - connection data (host,db,pass) - getDataSet() – defines state of DB before each test
  • 18. DB testing  Once setting up the ‘fake’ db connection tests can be executed to check queries  The db changes that occur during the tests don’t persist  Can verify number of rows after insertion, check query results, etc.  This is the safest way of fully testing an application (versus mocking db connection)
  • 19. Skeleton Generator  Automatically generates test classes based on assertions in the code
  • 20. IDE integration  Integrated in most ides: Eclipse, NetBeans, PhpStorm, etc
  • 21. Code coverage  Generating statistics with naked PhpUnit  phpunit -c app/ --coverage-html={foldername}
  • 24. Q&A