SlideShare une entreprise Scribd logo
1  sur  11
Télécharger pour lire hors ligne
Unit Testing in PHP
Lee Boynton
Advantages to Automating Testing
● Faster to test
○ Don't need to "click about"
○ Don't need to login
○ Don't need to have commented out test code
● Prevent recurring bugs
○ Write a test for bug, run the test after every change
● Easier to test edge cases
● Less fear when making changes
○ You may have forgotten how the code works
○ You may inherit someone else's code
● Find bugs before your users
○ This means you keep your customers happy, this
means more money!
Advantages to Automating Testing
● Better designed code, especially with TDD
○ Unit tested code tends to be
■ Less coupled
■ Less complex
● Tests document how code should work
● Once you are good at unit testing, it's
probably faster
● Tests don't have to be amazing: "Imperfect
tests, run frequently, are much better than
perfect tests that are never written at all"
Disadvantages
● You have to suck it up and write tests to
really see the benefits
● Hard to retrofit tests
○ You may have to refactor old code, or
○ You may have to write a lot of test code for code
which is not easy to test
● Harder to write bad code
● You probably won't want to write code
without tests again
Goals When Writing Tests
● Tests should be
○ Simple
■ Don't have ifs or loops
○ Easy to write
○ Easy to read
○ Easy to run
○ Isolated
● But these ideas may conflict or be hard to
achieve
○ Do your best
○ Can improve tests over time
○ Bad tests better than no tests
Common PHPUnit Methods
● $this->assertTrue($value, 'Value should
have been true')
● $this->assertFalse($value, 'Value should
have been false')
● $this->assertEquals($expected, $actual,
'The result is not what was expected')
● Try to write a message to indicate what
specifically is being asserted
○ Easier to understand what's wrong instead of e.g.
"Failed asserting that false is true"
Common PHPUnit Patterns
● Use setUp() method to instantiate the class
you are testing
○ This works well if you don't have lots of constructor
parameters
● Use data providers to test lots of different
inputs
○ Tests shouldn't have duplicate code either
● Use tearDown() method if you need to clean
up external resources after each test is run
○ Files
○ Database
Hard to Test Things
● Static calls to other classes
○ You cannot mock the dependency
● Singletons
○ Constructor is private or protected
○ Uses static call to get instance
○ Cannot guarantee there are no side effects when
running multiple tests
● Private methods
○ Usually you indirectly test these when you test public
methods
○ Can use reflection if you really want, but this
probably means you should refactor
Hard to Test Things
● Hard coded dependencies
○ Such as when a class instantiates another class
● Magic methods
○ __call
○ __get
○ __set
How to Write Testable Code
● Use dependency injection
○ This means you don't instantiate classes unless
you're in a factory
● Keep methods relatively small
● Avoid having lots of private methods
● Write classes which do one thing (single
responsibility principle)
Go go go!
● http://www.phpunit.
de/manual/current/en/index.html

Contenu connexe

En vedette

En vedette (6)

PHP Doesn't Suck
PHP Doesn't SuckPHP Doesn't Suck
PHP Doesn't Suck
 
PHP and node.js Together
PHP and node.js TogetherPHP and node.js Together
PHP and node.js Together
 
PHP meets NodeJS
PHP meets NodeJSPHP meets NodeJS
PHP meets NodeJS
 
PHP + Node.js
PHP + Node.jsPHP + Node.js
PHP + Node.js
 
Integrating Node.js with PHP
Integrating Node.js with PHPIntegrating Node.js with PHP
Integrating Node.js with PHP
 
How Google Works
How Google WorksHow Google Works
How Google Works
 

Similaire à Unit testing in PHP

Effective Unit Testing
Effective Unit TestingEffective Unit Testing
Effective Unit TestingEyal Kenig
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017Xavi Hidalgo
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy codeLars Thorup
 
Writing Tests Effectively
Writing Tests EffectivelyWriting Tests Effectively
Writing Tests EffectivelyPaul Boocock
 
Demise of test scripts rise of test ideas
Demise of test scripts rise of test ideasDemise of test scripts rise of test ideas
Demise of test scripts rise of test ideasRichard Robinson
 
Writing clean scientific software Murphy cleancoding
Writing clean scientific software Murphy cleancodingWriting clean scientific software Murphy cleancoding
Writing clean scientific software Murphy cleancodingsaber tabatabaee
 
Unit testing
Unit testingUnit testing
Unit testingPiXeL16
 
Writing Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkWriting Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkPeter Kofler
 
Test automation expert days
Test automation   expert daysTest automation   expert days
Test automation expert daysOren Rubin
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With PytestEddy Reyes
 
An insight to test driven development and unit testing
An insight to test driven development and unit testingAn insight to test driven development and unit testing
An insight to test driven development and unit testingDharmendra Prasad
 
The Art of Unit Testing Feedback
The Art of Unit Testing FeedbackThe Art of Unit Testing Feedback
The Art of Unit Testing FeedbackDeon Huang
 
Test Driven Development en Go con Ginkgo y Gomega
Test Driven Development en Go con Ginkgo y GomegaTest Driven Development en Go con Ginkgo y Gomega
Test Driven Development en Go con Ginkgo y GomegaSoftware Guru
 
Selenium done right
Selenium done rightSelenium done right
Selenium done rightTal Landa
 
Software Testing
Software TestingSoftware Testing
Software TestingAndrew Wang
 
Php Inspections (EA Extended): The Cookbook
Php Inspections (EA Extended): The CookbookPhp Inspections (EA Extended): The Cookbook
Php Inspections (EA Extended): The CookbookVladimir Reznichenko
 
Pen Testing, Red Teaming, and More
Pen Testing, Red Teaming, and MorePen Testing, Red Teaming, and More
Pen Testing, Red Teaming, and MoreCTruncer
 

Similaire à Unit testing in PHP (20)

Effective Unit Testing
Effective Unit TestingEffective Unit Testing
Effective Unit Testing
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Writing Tests Effectively
Writing Tests EffectivelyWriting Tests Effectively
Writing Tests Effectively
 
Demise of test scripts rise of test ideas
Demise of test scripts rise of test ideasDemise of test scripts rise of test ideas
Demise of test scripts rise of test ideas
 
Writing clean scientific software Murphy cleancoding
Writing clean scientific software Murphy cleancodingWriting clean scientific software Murphy cleancoding
Writing clean scientific software Murphy cleancoding
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Writing Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkWriting Tests with the Unity Test Framework
Writing Tests with the Unity Test Framework
 
Test automation expert days
Test automation   expert daysTest automation   expert days
Test automation expert days
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 
An insight to test driven development and unit testing
An insight to test driven development and unit testingAn insight to test driven development and unit testing
An insight to test driven development and unit testing
 
Ui Testing with Ghost Inspector
Ui Testing with Ghost InspectorUi Testing with Ghost Inspector
Ui Testing with Ghost Inspector
 
The Art of Unit Testing Feedback
The Art of Unit Testing FeedbackThe Art of Unit Testing Feedback
The Art of Unit Testing Feedback
 
UPC Plone Testing Talk
UPC Plone Testing TalkUPC Plone Testing Talk
UPC Plone Testing Talk
 
Test Driven Development en Go con Ginkgo y Gomega
Test Driven Development en Go con Ginkgo y GomegaTest Driven Development en Go con Ginkgo y Gomega
Test Driven Development en Go con Ginkgo y Gomega
 
Selenium done right
Selenium done rightSelenium done right
Selenium done right
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Php Inspections (EA Extended): The Cookbook
Php Inspections (EA Extended): The CookbookPhp Inspections (EA Extended): The Cookbook
Php Inspections (EA Extended): The Cookbook
 
Pen Testing, Red Teaming, and More
Pen Testing, Red Teaming, and MorePen Testing, Red Teaming, and More
Pen Testing, Red Teaming, and More
 

Dernier

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 MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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...Drew Madelung
 
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...Igalia
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Dernier (20)

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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[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
 
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...
 
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...
 
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...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Unit testing in PHP

  • 1. Unit Testing in PHP Lee Boynton
  • 2. Advantages to Automating Testing ● Faster to test ○ Don't need to "click about" ○ Don't need to login ○ Don't need to have commented out test code ● Prevent recurring bugs ○ Write a test for bug, run the test after every change ● Easier to test edge cases ● Less fear when making changes ○ You may have forgotten how the code works ○ You may inherit someone else's code ● Find bugs before your users ○ This means you keep your customers happy, this means more money!
  • 3. Advantages to Automating Testing ● Better designed code, especially with TDD ○ Unit tested code tends to be ■ Less coupled ■ Less complex ● Tests document how code should work ● Once you are good at unit testing, it's probably faster ● Tests don't have to be amazing: "Imperfect tests, run frequently, are much better than perfect tests that are never written at all"
  • 4. Disadvantages ● You have to suck it up and write tests to really see the benefits ● Hard to retrofit tests ○ You may have to refactor old code, or ○ You may have to write a lot of test code for code which is not easy to test ● Harder to write bad code ● You probably won't want to write code without tests again
  • 5. Goals When Writing Tests ● Tests should be ○ Simple ■ Don't have ifs or loops ○ Easy to write ○ Easy to read ○ Easy to run ○ Isolated ● But these ideas may conflict or be hard to achieve ○ Do your best ○ Can improve tests over time ○ Bad tests better than no tests
  • 6. Common PHPUnit Methods ● $this->assertTrue($value, 'Value should have been true') ● $this->assertFalse($value, 'Value should have been false') ● $this->assertEquals($expected, $actual, 'The result is not what was expected') ● Try to write a message to indicate what specifically is being asserted ○ Easier to understand what's wrong instead of e.g. "Failed asserting that false is true"
  • 7. Common PHPUnit Patterns ● Use setUp() method to instantiate the class you are testing ○ This works well if you don't have lots of constructor parameters ● Use data providers to test lots of different inputs ○ Tests shouldn't have duplicate code either ● Use tearDown() method if you need to clean up external resources after each test is run ○ Files ○ Database
  • 8. Hard to Test Things ● Static calls to other classes ○ You cannot mock the dependency ● Singletons ○ Constructor is private or protected ○ Uses static call to get instance ○ Cannot guarantee there are no side effects when running multiple tests ● Private methods ○ Usually you indirectly test these when you test public methods ○ Can use reflection if you really want, but this probably means you should refactor
  • 9. Hard to Test Things ● Hard coded dependencies ○ Such as when a class instantiates another class ● Magic methods ○ __call ○ __get ○ __set
  • 10. How to Write Testable Code ● Use dependency injection ○ This means you don't instantiate classes unless you're in a factory ● Keep methods relatively small ● Avoid having lots of private methods ● Write classes which do one thing (single responsibility principle)
  • 11. Go go go! ● http://www.phpunit. de/manual/current/en/index.html