SlideShare a Scribd company logo
1 of 235
Getting Started with Test-Driven
Development
Scott Keck-Warren
Longhorn PHP 2023
@scottKeckWarren@phpc.social
https://tinyurl.com/tdd-longhorn-2023
Change
Change
Is Scary
Change
Is Stressful
Change
“Breaks” Production
“Don’t Push on Friday”
Testing “Goals” Module
7 Steps X 2 Users X 2 Modes = 10+ Minutes To Test
Testing “Goals” Module
• Brittle
• Lots of time consuming testing
• Annoyed Scott
I Needed Confidence
Automated Tests = Confidence
Test-Driven Development
Getting Started with Test-Driven
Development
Scott Keck-Warren
Longhorn PHP 2023
@scottKeckWarren@phpc.social
Scott Keck-Warren
Director of Technology
@ WeCare Connect
Scott Keck-Warren
PHP Developer
Scott Keck-Warren
Director of Technology
@ WeCare Connect
Scott Keck-Warren
Host
@ PHP[Architect] YouTube
Channel
https://www.youtube.com/phparch
Agenda
Agenda
1. What Is Test-Driven Development?
2. Why You Should Be Using Test-Driven
Development?
3. How To Do Test-Driven Development?
4. Unit and Feature Testing
5. What is Code Coverage?
What is Test-Driven
Development (TDD)?
TDD:
A test-first software development
process that uses short
development cycles to write very
specific test cases and then modify
our code so the tests pass.
What is Test-Driven Development?
• Short cycles of 5 phases
• Less Minute
• Dozens/hundreds of cycles each day
Add A
New Test
Run All
Tests to
See
Failures
Make a
change
Run Tests
to See
Success
Refactor
Why Use Test-Driven
Development?
Why Use Test-Driven Development?
• Using TDD generate Automated Test Suite
• Infinitely repeatable
• Automated Test Suite Gives Us Confidence!
Why Use Test-Driven Development?
7 Steps X 2 Users X 2 Modes = 10+ Minutes To Test
Manual
Why Use Test-Driven Development?
7 Steps X 2 Users X 2 Modes = 10+ Minutes To Test
200+ Automated Tests
Why Use Test-Driven Development?
7 Steps X 2 Users X 2 Modes = < 2 Minutes To Test
200+ Automated Tests
Why Use Test-Driven Development?
Cycle Type: 2 Days
Why Use Test-Driven Development?
Cycle Type: 2 Days
Why Use Test-Driven Development?
Cycle Type: 2 Days
2 Hours
How Do You Do Test Driven
Development?
Add A
New Test
Run All Tests to
See Failures
Make a change
Run Tests to
See Success
Refactor
Add A
New Test
Run All
Tests to
See
Refactor
Add A
New Test
Run All
Tests to
See
Failures
or
Add A
New Test
Run All
Tests to
See
Failures
or
Failures
Make a
change
Run Tests
to See
Success
Failures
Make a
change
Run Tests
to See
Success
Add A
New Test
R
T
F
Refactor
Refactor:
Restructure so as to improve operation
without altering functionality
#5. Refactor
TDD + Refactoring
=
No Happy Accidents
Add A
New Test
R
T
F
Refactor
Add A
New Test
Run All
Tests to
See
Failures
Make a
change
Run Tests
to See
Success
Refactor
Unit Test Example
Unit Tests:
Test single class/module in
isolation
Value Objects in
About a Minute
Value Objects
1.Structural Equality
2.Immutability
3.Self-validation
src/Location/City.php
Testing Framework/Tool
PHPUnit
PHPUnit
• Testing Framework
• All tests are written in PHP
PHPUnit
• Organization is easy
• Test files inside a tests folder
• A PHP class groups similar tests together
• A test is a PHP class method
./vendor/bin/phpunit
./vendor/bin/phpunit tests/Location/CityTest.php
./vendor/bin/phpunit —filter User
Framework + IDE = More Efficiency
./vendor/bin/phpunit tests/Location/CityTest.php
Unit Test Example
Add A
New Test
src/Location/City.php
tests/Location/City.php
tests/Location/CityTest.php
Run All
Tests to
See
Failures
Make a
change
Run Tests
to See
Success
Refactor
Another Day Another Test
Add A
New Test
Run All
Tests to
See
Failures
Make a
change
Run Tests
to See
Success
Refactor
isNotEmpty()
vs
Add A
New Test
Run All
Tests to
See
Failures
Make a
change
Run Tests
to See
Success
Refactor
Unit Test Example
Feature Test Example
Feature Test
Tests application as user would interact with it
Pest
PHPUnit
Pest
• Test files inside a tests/unit or tests/feature folder
• A test is a PHP function
• A “.php” file groups common tests
./vendor/bin/pest
./vendor/bin/pest tests/Unit/Location/CityTest.php
./vendor/bin/pest —filter User
As a user, provide a page that lists all GitHub repositories the user has
access to
Feature Test Example
User
User Server
Server
GitHub
GitHub
/repositories/all
API Call
JSON
HTML
Feature Test Example
User
User Server
Server
GitHub
GitHub
/repositories/all
API Call
JSON
HTML
AppServiceGitHub
AppProvidersAppServiceProvider
Add A
New Test
RepositoryControllerTest.php
RepositoryControllerTest.php
RepositoryControllerTest.php
RepositoryControllerTest.php
RepositoryControllerTest.php
Run All
Tests to
See
Failures
Make a
change
routes/auth.php
RepositoryController.php
RepositoryController.php
Run Tests
to See
Success
Refactor
Feature Test Example
User
User Server
Server
GitHub
GitHub
/repositories/all
API Call
JSON
HTML
Add A
New Test
RepositoryControllerTest.php
Run All
Tests to
See
Failures
Make a
change
RepositoryController.php
RepositoryController.php
RepositoryController.php
RepositoryController.php
AppServiceGitHub
AppServiceGitHub
Feature Test Example
User
User Server
Server
GitHub
GitHub
/repositories/all
API Call
JSON
HTML
Options?
1. Ignore It and Hope for the Best
2. Give my access token to the tests
3. Mock it!
Mocking:
Help isolate the external
dependency to make it easier to
test
Mockery_2_App_Service_GitHub
Mocking
AppServiceGitHub
getAllRepositoriesForCurrentUser()
isAuthenticated()
getAllRepositoriesForCurrentUser()
RepositoryControllerTest.php
RepositoryControllerTest.php
RepositoryControllerTest.php
RepositoryControllerTest.php
RepositoryControllerTest.php
RepositoryControllerTest.php
RepositoryControllerTest.php
Run Tests
to See
Success
Refactor
Feature Test Example
What is Code Coverage?
Code Coverage:
A software testing metric that
determines how much of your
code is run during your test
process.
What is Code Coverage?
Executed Lines / Total Lines * 100
What is Code Coverage?
What is Code Coverage?
What is Code Coverage?
What is Code Coverage?
What is Code Coverage?
What is Code Coverage?
Executed / Total * 100
What is Code Coverage?
1 / Total * 100
What is Code Coverage?
1 / 2 * 100
What is Code Coverage?
50%
What is Code Coverage?
What is Code Coverage?
XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-text
What is Code Coverage?
What's a Good Coverage
Number?
“It depends”
What's a Good Coverage Number?
75-90%
What's a Good Coverage Number?
< 75 => no confidence
What's a Good Coverage Number?
> 90 fragile, expensive
What's a Good Coverage Number?
Overall: 80%+
What's a Good Coverage Number?
Billing: 95%+
What is Code Coverage?
What is Code Coverage?
What You Need to Know
What You Need to Know
• TDD: test-first software development process
• Gives us confidence to make changes
• Five short phases
• Each of the phases happens very quickly
• Don’t neglect to refactor
What You Need to Know
Add A
New Test
Run All
Tests to
See
Failures
Make a
change
Run Tests
to See
Success
Refactor
What You Need to Know
• Use a testing framework like PHPUnit/Pest
• Write clear and concise tests
• Unit tests: tests code in isolation
• Feature tests: tests code as user interacts with it
• Code coverage determines if our code has enough tests
Thank The Sponsors!
Thank The Sponsors!
Thank The Organizers!
Thank The Speakers!
Thank Scott!
• Feedback on joind.in
• Follow me on my socials
• @scottkeckwarren@phpc.social
• scottkeckwarren on:
• TikTok/Twitch/X
• Subscribe to YouTube Channel
Questions?
• Scott Keck-Warren
• Resources:
• https://tinyurl.com/tdd-longhorn-2023

More Related Content

Similar to Getting Started with Test-Driven Development at Longhorn PHP 2023

How to Fit Performance Testing into a DevOps Environment
How to Fit Performance Testing into a DevOps EnvironmentHow to Fit Performance Testing into a DevOps Environment
How to Fit Performance Testing into a DevOps EnvironmentNeotys
 
Test Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionTest Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionPyxis Technologies
 
ISTQB Foundation - Chapter 2
ISTQB Foundation - Chapter 2ISTQB Foundation - Chapter 2
ISTQB Foundation - Chapter 2Chandukar
 
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015Cloud and Network Transformation using DevOps methodology : Cisco Live 2015
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015Vimal Suba
 
Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)Abhijeet Vaikar
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentbhochhi
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...AgileNetwork
 
How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.Matt Eland
 
Quality Loopback
Quality LoopbackQuality Loopback
Quality LoopbackOmar Bashir
 
TDD and Unit Testing in Golang
TDD and Unit Testing in GolangTDD and Unit Testing in Golang
TDD and Unit Testing in GolangSofian Hadiwijaya
 
Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010guest5639fa9
 
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose presoTest Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose presoElad Elrom
 
Software presentation
Software presentationSoftware presentation
Software presentationJennaPrengle
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 

Similar to Getting Started with Test-Driven Development at Longhorn PHP 2023 (20)

DevTestOps
DevTestOpsDevTestOps
DevTestOps
 
How to Fit Performance Testing into a DevOps Environment
How to Fit Performance Testing into a DevOps EnvironmentHow to Fit Performance Testing into a DevOps Environment
How to Fit Performance Testing into a DevOps Environment
 
Test Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionTest Driven Development - Overview and Adoption
Test Driven Development - Overview and Adoption
 
ISTQB Foundation - Chapter 2
ISTQB Foundation - Chapter 2ISTQB Foundation - Chapter 2
ISTQB Foundation - Chapter 2
 
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015Cloud and Network Transformation using DevOps methodology : Cisco Live 2015
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015
 
Agile Testing - What is it?
Agile Testing - What is it?Agile Testing - What is it?
Agile Testing - What is it?
 
Agile Testing
Agile Testing  Agile Testing
Agile Testing
 
Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)
 
Methodology: IT test
Methodology: IT testMethodology: IT test
Methodology: IT test
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
 
How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.
 
Quality Loopback
Quality LoopbackQuality Loopback
Quality Loopback
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
TDD and Unit Testing in Golang
TDD and Unit Testing in GolangTDD and Unit Testing in Golang
TDD and Unit Testing in Golang
 
Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010
 
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose presoTest Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
 
Software presentation
Software presentationSoftware presentation
Software presentation
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd   seven years afterIan Cooper webinar for DDD Iran: Kent beck style tdd   seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
 

More from Scott Keck-Warren

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Scott Keck-Warren
 
Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021Scott Keck-Warren
 
Developing a Culture of Quality Code at Givelify (Tech Talk)
Developing a Culture of Quality Code at Givelify (Tech Talk)Developing a Culture of Quality Code at Givelify (Tech Talk)
Developing a Culture of Quality Code at Givelify (Tech Talk)Scott Keck-Warren
 
Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)Scott Keck-Warren
 

More from Scott Keck-Warren (6)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023
 
Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021
 
Developing a Culture of Quality Code at Givelify (Tech Talk)
Developing a Culture of Quality Code at Givelify (Tech Talk)Developing a Culture of Quality Code at Givelify (Tech Talk)
Developing a Culture of Quality Code at Givelify (Tech Talk)
 
Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

Getting Started with Test-Driven Development at Longhorn PHP 2023

Editor's Notes

  1. As humans, change can be scary
  2. My grocery store changed layout and couldn’t find coffee for three weeks
  3. As developers, we know that change breaks production No mater how small the change I’ve fixed a spelling error in a string and created a bug That leads to…<click>
  4. Whose heard this one before <slide> That’s way my mantra because I don’t want to have to boot my work computer up on Sunday
  5. Maintained a module to set professional development goals Process had seven steps <click> Alternated between supervisor and direct <click> Two “modes” <click> Testing took a minimum of 10 minutes<click> Manual so Error prone. Sometimes I would make a mistake in step 2 and not realize to step 6 and have to start over God forbid I was on vacation and someone else made the change
  6. Because there we so many moving parts: <slide> Someone would say can we add a new feature I would say yes very reluctantly and then tell them 2 days minimum
  7. Confidence that I could make changes Not break anything Hard to do with all the manual testing Looked for a solution
  8. How do we create automated tests Lots of options
  9. Cloud image in the back TDD gave me that confidence
  10. For those of you who haven’t met me my name is …
  11. Professional PHP Developer for 15 years // team lead/CTO role for 10 of those 15
  12. Currently Director of Technology at WeCare Connect Survey solutions to improve employee and resident retention at skilled nursing facilities Use PHP for our backend Also …
  13. Create Educational Videos on PHPArchitect YouTube
  14. Discuss topics helpful for PHP developers If you want more content like this session follow me on social media and subscriber to our channel
  15. Found at youtube.com/phparch
  16. Could spend hours discussing automated testing with you all. It’s one of my favorite PHP adjacent topics but we only have 50 minutes. My goals are to always have you leave one of my sessions with something you can use the next day you’re going to work and how you can implement this with your team
  17. TDD consists of five phases that we will repeat as we modify our code. Each of the phases happens very quickly and we might go through all five phases in less than a minute.
  18. Back to our goals module from before Problem was on this side because it was manual <click>
  19. Wrote 200+ automated tests for Goals Module Still had that complexity but I didn’t care
  20. Was 10 minutes now less 2 minutes Wasn’t even 2 active minutes I could step away from my computer Could confidently make a changes Didn’t forget steps Cycle time dropped from days to hours
  21. Cycle time dropped from days
  22. To
  23. Hours
  24. Abstract then concrete
  25. TDD consists of 5 SHORT phases < ten new lines of code being modified. If we find ourselves doing more than that we're working on too large a change and we need to break it into smaller pieces.
  26. The first thing we're going to do is write a failing test. We'll use this failing test to help determine when we've achieved our expected functionality.
  27. 2. Run all tests and see the new one fail In this step, we're going to run the test to make sure our test fails before we move on to the next phase. It's very easy to write a test that doesn't fail so we **always** run our test to verify it's failing before moving to the next phase. If it’s not failing we don’t know if our change actually did anything
  28. As a small aside, the wording for this phase says "run all the tests" but as our test suite (a collection of tests) grows this will take an unproductively large amount of time. Current code base takes 25 minutes to run whole suite. We'll want to short circuit this and only run the test file or just our new test.
  29. 3. Make a little change Now our goal is to change the smallest amount of code possible to get that test to pass. We don't want to change any more than is necessary because that extra bit of change wasn't made using TDD and is potentially not tested. We don't need perfect code in this phase we just need code that makes the test pass. It's very easy to get caught up in making sure everything is perfect but that's not the goal here. Perfect comes later.
  30. 4. Run all tests and see them all succeed Now that we've made our change we can run our test and see that it passes new test and any other tests. If it doesn't then we just jump back to phase #3 and keep making small changes until it does.
  31. 5. Refactor to remove duplication Now that we have our tests passing we're going to take a break and inspect both our test code and our code under test to see where we can make changes so it's easier for future developers to read, understand, and maintain.
  32. This is called Refactoring and it’s: restructure code so as to improve operation without altering functionality.
  33. We're using TDD so changes are painless because we can quickly run our unit tests again to make sure we didn't make a mistake.
  34. Now that we've completed a single TDD cycle we can start back at the beginning with a new test.
  35. If you google TDD There’s also a three phase version Called Red, green, refactor Red and green come from colored messages we get from our testing tool Basically group phases 1 and 2 and 3 and 4. I like 5 phases because it gives explicit steps
  36. This has been all very abstract so lets make it more concrete
  37. Fast Good starting point for new classes
  38. Been working on an open source project for the YouTube Channel Value objects
  39. Did a whole video on how awesome value objects are Nee
  40. Custom classes for each domain type in our application Provide three things
  41. Problem they solve is this Have a function to recreate user Need first, last, email
  42. Later call the function Made an Oops <click>
  43. Should be <comment order> Did email first Tricky kind of bug Dare you to find this in code review
  44. Now I can’t mess up calling this And Helper functions
  45. before we go further This is a contrived example Feel free to roll your eyes as I’m doing stupid things to make my point Don’t use this as evidence for a future job
  46. I have this value object class to track a City Only important thing is that we’re storing our information in $value property Want to add more functionality using TDD
  47. First thing we need is a <slide>
  48. This example uses PHPUnit to run our tests as the project is already using phpunit Talk about the other framework later
  49. In case you don’t know Testing Framework All tests are written in PHP so we don’t need to learn anything new
  50. Organization is easy All test files are placed inside a tests folder at the root of the project A test is a PHP class method
  51. Each test function starts with “test” or …
  52. uses the @test annotation This is a personal preference thing. I learned PHPUnit before annoation option so I default to prefixing tests with test. Also uses less vertical space which helpful for presentations
  53. Might notice assert function calls Each test function contains one or more asserts
  54. Asserts tell PHPUnit to compare an expected value to the value we got from our codeEach test contains one or more asserts Compare output values <click> Compare expected value vs output <click> Check for greater than or equal <click>
  55. Command line tool Super powerful
  56. Run a single file
  57. Use filter to reduce runs Example anything that involves users
  58. Our examples today mostly command line Running using ./vendor/bin/phpunit tests/FileTest.php
  59. 1. Add a new test
  60. No tests for City because there wasn’t any logic to test First step is to create the test file <screen> is current file
  61. Swap tests for src
  62. And append test That way can easily find tests for city class
  63. Start with our blank file
  64. Create class Class name needs to match the file name -> new PHPunit doesn’t like mismatch
  65. Extends PHPUnit\Framework\TestCase . TestCase class gives us asserts and setup logic we need This is just boiler plate so far Remember this when we talk about Pest
  66. Let’s remember what we want to do because I’ve rambled Not sure how I want to do this so let’s start coding and figure it out
  67. Create the test function. We’re going to name the function based on what we’re testing to it’s easier to understand when future us comes back to it.
  68. Create Our Initial Conditions
  69. Run the code we’re going to test
  70. Assert the results Don’t like the useless variable here so we’ll get rid of it
  71. Notice how small the actual test is. We're giving the test a very specific functionality to test and we're only asserting one thing. If we have more than one assert per test we run the risk of making it difficult to debug later when something breaks.
  72. 2. Run all tests and see the new one fail
  73. Now we'll run PHPUnit to see that we do indeed get a failing test.
  74. In this case, we haven't yet defined the method so we get an "undefined method" error. Red message -> in an error state like we saw in red/green/refactor
  75. 3. Make a little change To reiterate, our goal in this phase is to make the smallest change we can to allow our tests to pass. Two options here: <click>
  76. add in the obvious implementation Obvious means is a few lines that we can’t possibility mess up the logic for This case just call to mb_strlen
  77. 2 - Make the smallest possible change by returning true always. It doesn't cover all the possible inputs but the goal in this step isn't to cover all the inputs it's to get our test to pass. We'll cover more inputs later.
  78. We’re going to want to show another cycle of TDD so we’re going to just return true
  79. 4. Run all tests and see them all succeed
  80. Now we run our test and verify that our test passes. Notice green from red/green/refactor
  81. 5. Refactor
  82. Our simple implementation of `somefunction()` is going to be wrong most of the time because of its current implementation. Now we need to add another test that checks for other cases where the string isn't empty. As a general rule, it's a good idea to have tests for normal input, the extremes of inputs (very large or very small), and spots where we can think of oddities happening obviously very domain specific We’re going to check for a case where the string isn’t empty to add an addition testing point
  83. 1. Add a new test
  84. Add a new test What we have currently
  85. Add in the opposite
  86. 2. Run all tests and see the new one fail
  87. This time we get a failure assertion that true is false
  88. 3. Make a little change
  89. Look at our original code Could change to return false but that would cause other tests to fail
  90. Back to the obvious implementation we had before
  91. 4. Run all tests and see them all succeed
  92. 5. Refactor
  93. We have working code that fulfills the requirements Right? Done? Maybe? Let’s look at how this looks in usage
  94. Basic if block I’m going to come across someFunction and have no idea what it is Going to slow me down and that’s annoying Excellent time to refactor and pick a new name Lots of options
  95. Don’t like this because its a verb so we could be performing an action
  96. isEmpty sounds good to me Sounds like a sentence
  97. Back to our code now
  98. After refactor Subjectively better?
  99. No happy accidents
  100. Starting to get the hang of this Adding a test now to check for a string that isn’t empty.
  101. Could do !isEmpty() but isNotEmpty is actually easier for us to process as programmers so it’s nice to have Also contrived example
  102. 1. Add a new test
  103. Again small Again written so we know what’s going on quickly
  104. 2. Run all tests and see the new one fail
  105. 3. Make a little change
  106. In this case instead of returning `false` and then creating another test so we can write the functionality by going through all the TDD steps, we're just going to trust ourselves and create the obvious implementation of the `isNotEmpty()` function.
  107. 4. Run all tests and see them all succeed
  108. Oh good we didn’t make any mistakes
  109. 5. Refactor to remove duplication Now here is where it gets interesting.
  110. The last two times we've hit this step we haven't had anything to do but now look at our `isEmpty()` and `isNotEmpty()` functions.
  111. We can see some minor duplication in the two calls to `mb_strlen($this->string)`. Now we just need to determine how we want to resolve this. 2 options: Option 1 is to extract that duplication into a new function.
  112. Call it length and copy duplication into body Extracting a new function is favorite refactor because it makes the code more readable and because we'll most likely need the same logic again.
  113. Now The replace the calls with the new function
  114. The second option is to realize that `isNotEmpty()` returns the boolean opposite of `isEmpty()` and just use it
  115. If I hadn’t been working through this example just to get to this who cares example I think I would have done this automatically. The first option gives us the best flexibility for future expansion but second less code. Always a fond of less code
  116. Finally, we need to run our tests again to verify that no accidents crept into our code as we made these changes.
  117. That’s how we do unit tests Until today this is where the “coding” piece ended Someone on joind.in gave me feedback that it was too simple so
  118. In our example, we worked out an example of tests where we only tested a single class. Generally that’s where these presentations stop but we can do better right
  119. Slower than unit tests Working with local databases and services Great for high coverage (discuss later)
  120. Over on my Twitch stream slowly working on this Tool to help with Pull Requests Lots of ideas on what to do Time to tackle another item off my backlog
  121. Wanted to use all the newest/greatest projects in PHP space for this project so using Pest Testing Framework <click>Built on top of PHPUnit Can use with existing PHPunit tests There are some differences
  122. Organization is easy All test files are placed inside a tests folder at the root of the project A test is a PHP function
  123. Uses expectation API
  124. Built on top of PHPUnit so we can still use assertion api I love how expressive the expectation API is but tend to fall back to assertions
  125. Command line tool Super powerful Again run with not parameters to run all tests
  126. Run a single file
  127. Use filter to reduce runs Example anything that involves users
  128. Maybe this is more complicated? Let’s look at a flow diagram of what we’re doing <Click through steps> It’s a lot right? Don’t feel like I can write an easy test for this
  129. Tackle one small piece only First test: Can access /organizations/all
  130. Only thing that exists now: GitHub service Takes the current user’s OAuth token and creates a connection to GitHub using 3rd party package
  131. Only thing that exists now: GitHub service Takes the current user’s OAuth token and creates a connection to GitHub
  132. 1. Add a new test
  133. 2. Run all tests and see the new one fail
  134. 3. Make a little change To reiterate, our goal in this phase is to make the smallest change we can to allow our tests to pass. Two options here: <click>
  135. It doesn’t do anything but again smallest amount of code possible
  136. 4. Run all tests and see them all succeed
  137. 5. Refactor to remove duplication Kept it DRY to start so we’re good
  138. Second test the rest?
  139. 1. Add a new test
  140. 2. Run all tests and see the new one fail
  141. 3. Make a little change To reiterate, our goal in this phase is to make the smallest change we can to allow our tests to pass. Two options here: <click>
  142. I’m going to ignore creating the blade file here because it’s not interesting and hard to read
  143. getAllRepositoriesForCurrentUser
  144. Break with process and see actually results
  145. Uggg, look at all the abandoned side projects <click> But do see ScottsValueObjects
  146. External Dependency Have zero control over it Data might change Worse it requires: login active connection to internet
  147. Use a library This case we’re using Mockery library Allows us to specify return values from functions
  148. Pest has support to override the service container for our mock
  149. 4. Run all tests and see them all succeed
  150. Uggg, look at all the abandoned side projects But do see ScottsValueObjects
  151. 5. Refactor to remove duplication Again dry code so no refactoring
  152. That’s a feature test Small amount of testing code tests large amount of user land code Allows for high code coverage
  153. The "total number of lines of code" only includes lines that are performing operations and not declarations and white space.
  154. As an example, this class
  155. Single test to see that we can initialize our class
  156. Let’s see what our coverage is
  157. Only two lines are executable
  158. Only the assignment is actually run during this test
  159. Calcaluation on the board to help us
  160. <result> Manual isn’t going to work because our code is always changing
  161. Thankfully
  162. Need to also have XDEBUG or another tool installed SET mode to coverage
  163. Spits out same result
  164. < 75% -> hard to feel confident making changes
  165. > 90% -> fragile, expensive tests
  166. Personally my team targets 80%
  167. Missing critical stuff we target 95% Want to make this part of our
  168. Running at the command line also is a little rough so I like to include it in my CI/CD runs Like to use Codecov but there’s a million of these SaaS companies that do this
  169. Spits out results in our PR
  170. Also shows lines that aren’t being covered by a test
  171. 1. Add a new test 2. Run all tests and see the new one fail 3. Make a little change 4. Run all tests and see them all succeed 5. Refactor to remove duplication
  172. Add QR code here
  173. Add QR code here